<?php


namespace app\api\controller\v1;


use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use other\MessageSend;
use other\SmsMuSend;
use other\SmsWYSend;
use think\Db;
use think\Log;
use think\Queue;
use app\common\model\Clue as ClueModel;
use app\api\model\Clue as ApiClueModel;

class Clue
{


    //线索撞库
    public function checkPhone(){
        $post = file_get_contents("php://input");
        $postData = json_decode($post, true);
        if(empty($_GET['adv_id'])){
            return Json(['errCode' => 202, 'msg' => '参数缺失', 'code' => 202]);
        }
        $aid = $_GET['adv_id'];
        $insertLog = [
            'api_url' => '撞库',
            'adv_id' => $aid,
            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
            'name' => isset($postData['username']) ? $postData['username'] : '',
            'city' => isset($postData['city']) ? $postData['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);

        if(empty($postData['mobile'])){
            return Json(['errCode' => 202, 'msg' => '电话不能为空', 'code' => 202]);
        }
//        $isDayPhone = (new ClueModel())->isRepeatClue($postData['phone'], $postData['adv_id']);
//        if ($isDayPhone) {
//            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
//            throw new ParamException(['msg' => '手机号已存在!', 'errCode' => 202,'code'=>202]);
//        }

        $isClue = model('clue')->where(['phone' => $postData['mobile']])->find();
        if($isClue){
            ApiClueModel::setClueApiLogError($apiId, '线索手机重复');
            return Json(['errCode' => 202, 'msg' => '线索手机重复', 'code' => 202]);
        }

        return Json(['code' => 200,'errCode'=>200, 'msg' => '手机号不存在!','data'=>'']);
    }

    public function shanghaiPush()
    {

        $post = file_get_contents("php://input");
//        Log::record($post, 'error');
//        Log::record($_GET, 'error');

        $postData = json_decode($post, true);

        $aid = 7788;
        $insertLog = [
            'api_url' => '上海沪银',
            'adv_id' => $aid,
            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
            'name' => isset($postData['username']) ? $postData['username'] : '',
            'city' => isset($postData['city']) ? $postData['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);

        if (empty($postData['username'])) {
            ApiClueModel::setClueApiLogError($apiId, 'username不能为空');
            return Json(['msg' => 'username不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['mobile'])) {
            ApiClueModel::setClueApiLogError($apiId, 'mobile不能为空');
            return Json(['msg' => 'mobile不能为空',  'status' => 200, "code" => 500]);
        }

        if(empty($postData['city'])){
            ApiClueModel::setClueApiLogError($apiId, 'city不能为空');
            return Json(['msg'=>'city不能为空', 'status' => 200, "code" => 500]);
        }

//        if (empty($postData['remark'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'remark不能为空');
//            return Json(['msg' => 'remark不能为空',  'status' => 200, "code" => 500]);
//        }




        if(empty($postData['type'])){
            $pro_id=5;
        }else{
            if(isset($postData['isGjj']) && $postData['isGjj']==true){
                $pro_id=6;
            }elseif (isset($postData['gjj']) && $postData['gjj']==1){
                $pro_id=6;
            }elseif (isset($postData['house']) && $postData['house']==1){
                $pro_id=3;
            }elseif (isset($postData['car']) && $postData['car']==1){
                $pro_id=4;
            }elseif (isset($postData['credit']) && $postData['credit']==1){
                $pro_id=5;
            }
        }

        $params['clue_id'] = time() . mt_rand(1, 999999);
        $params['pro_id'] = $pro_id;;
        $params['adv_id'] = $aid;;
        $params['clue_name'] = $postData['username'];
        $params['phone'] = $postData['mobile'];
        $params['city'] = $postData['city'];
        $params['apply_limit'] = isset($postData['quota'])?$postData['quota']:0;
        $params['age'] = isset($postData['age'])?$postData['age']:0;
        $params['gender'] = isset($postData['sex'])?$postData['sex']:0;

        $isAid = Db::name('account')->where('adv_id', $aid)->find();

        if(!$isAid){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户不存在', $params);
            ApiClueModel::setClueApiLogError($apiId, '账户不存在');
            return Json(['msg' => '账户不存在',  'status' => 200, "code" => 500]);
        }
        if($isAid['status']!=1){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
            return Json(['msg' => '账户已禁用',  'status' => 200, "code" => 500]);
        }

        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
        if ($isBlack) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
            ApiClueModel::setClueApiLogError($apiId, '进线失败，黑名单线索');
            return Json(['msg' => '进线失败，黑名单线索',  'status' => 200, "code" => 500]);
        }

        $params['type']=$isAid['channel_id'];

        if($isAid['is_check_repeat']==1){
            $isClue=model('clue')->where('phone',$params['phone'])->find();
            if($isClue){
                $errMsg='API撞库：线索已存在';
                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),$errMsg,$params);
                ApiClueModel::setClueApiLogError($apiId, $errMsg);
                throw new ParamException(['msg'=>$errMsg,'status'=>200,'code'=>500]);
            }
        }

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //throw new ParamException(['msg' => '账户城市已禁用', 'errorCode' => 40001]);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001]);
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
        if ($is_allow === false) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁止');
            throw new ParamException(['msg' => '账户城市已禁止', 'errorCode' => 40001]);
        }

        $remark[]=isset($postData['remark']) ? $postData['remark'] : '';
        $params['remark']=json_encode($remark,JSON_UNESCAPED_UNICODE);

        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
        }

        $params['type']=$isAid['channel_id'];
//        if (empty($isAid)) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
//            return Json(['msg' => 'API线索接收失败，账户ID不存在', 'status' => 202, "data" => "error"]);
//        }


        if (strpos($params['city'], '|') !== false) {
            $city_t = explode('|', $params['city']);
        } elseif(strpos($params['city'], '-') !== false) {
            $city_t = explode('-', $params['city']);
        }else{
            $city_t=[$params['city']];
        }

        $city_info = clue_city_transform($city_t);

        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
//            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $city_info['pid'] . '-' . $city_info['id'];
        }

        $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price']=$clueCost['money'];
            $params['true_price']=$clueCost['money'];
            $params['xz_price']=$clueCost['money'];
            $params['xz_true_price']=$clueCost['money'];
            $params['xz_price2']=$clueCost['money'];
            $params['xz_true_price2']=$clueCost['money'];
        }else{
            $params['price']=$isAid['clue_cost'];
            $params['true_price']=$isAid['clue_cost'];
            $params['xz_price']=$isAid['clue_cost'];
            $params['xz_true_price']=$isAid['clue_cost'];
            $params['xz_price2']=$isAid['clue_cost'];
            $params['xz_true_price2']=$isAid['clue_cost'];
        }
        $params['account_id']=$isAid['id'];

        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
        }

        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (empty($params['city'])) {
            return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 200]);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
//        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE),'data'=>'success']);
    }


    //橙焦推送过来的
    public function cjPush(){
        $post = file_get_contents("php://input");

        $postData = json_decode($post, true);

        $aid = 99999;

        $insertLog = [
            'api_url' => '橙焦API',
            'adv_id' => $aid,
            'source_adv_id' => isset($postData['adv_id']) ? $postData['adv_id'] : '', //源头线索id
            'source_acc_name' => isset($postData['source_acc_name']) ? $postData['source_acc_name'] : '', //源头线索id
            'source_acc_desc' => isset($postData['source_acc_desc']) ? $postData['source_acc_desc'] : '', //源头线索id
            'phone' => isset($postData['phone']) ? $postData['phone'] : '',
            'name' => isset($postData['name']) ? $postData['name'] : (isset($postData['clue_name']) ? $postData['clue_name'] : '') ,
            'city' => isset($postData['city']) ? $postData['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
        $access_token='';

        $params=$postData;

        $isAid = Db::name('account')->where('adv_id', $aid)->find();
        if (empty($isAid)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
            return Json(['msg' => 'API线索接收失败，账户ID不存在', 'status' => 202, "data" => "error"]);
        }
        
        if($isAid['status']!=1){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            return Json(['msg' => '账户已禁用', 'status' => 202, "data" => "error"]);
        }

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            return Json(['msg' => '账户城市已禁用', 'status' => 202, "data" => "error"]);
        }


        //记录线索成本
        $clueCost=model('ClueAddCost')->where(['account_id'=>$isAid['id'],'pro_id'=>$params['pro_id'],'city'=>$params['city']])->find();
        if(!empty($clueCost)&&$clueCost['status']==1){
            $params['price']=$clueCost['money'];
            $params['true_price']=$clueCost['money'];
        }else{
            $params['price']=$isAid['clue_cost'];
            $params['true_price']=$isAid['clue_cost'];
        }
        $params['account_id']=$isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            return Json(['msg' => '线索接收失败', 'status' => 202, "data" => "error"]);
        }
        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1, 'phone'=>$params['phone'],'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (empty($params['city'])) {
            return Json(['status' => 200, 'msg' => '线索接收成功', 'data' => 'success']);
        }

        if ($access_token == 123456 || strpos($params['clue_name'], '测试') !== false) {
            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'data' => 'success']);
        }
        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//
//        $res = $this->cluePush($clue_info, true);


        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['status' => 200, 'msg' => '线索接收成功', 'data' => 'success']);

    }

    /* 捷融三方推送过来 */
//    public function jierongPush()
//    {
//
//        $post = file_get_contents("php://input");
////        Log::record($post, 'error');
////        Log::record($_GET, 'error');
//
//        $postData = json_decode($post, true);
//
//        $aid = isset($_GET['aid']) ? $_GET['aid'] : '';
//        $insertLog = [
//            'api_url' => '捷融API',
//            'adv_id' => $aid,
//            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
//            'name' => isset($postData['name']) ? $postData['name'] : '',
//            'city' => isset($postData['city']) ? $postData['city'] : '',
//            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
//            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
//            'create_time' => date('Y-m-d H:i:s')
//        ];
//        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
//        $access_token = isset($_GET['token']) ? $_GET['token'] : '';
//
//        if (empty($aid)) {
//            ApiClueModel::setClueApiLogError($apiId, '账户ID不能为空');
//            return Json(['msg' => '账户ID不能为空', 'status' => 202, "data" => "error"]);
//        }
//        if (empty($access_token)) {
//            ApiClueModel::setClueApiLogError($apiId, 'Token不能为空');
//            return Json(['msg' => 'Token不能为空', 'status' => 202, "data" => "error"]);
//        }
//
//        if (empty($postData['name'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'name不能为空');
//            return Json(['msg' => 'name不能为空', 'status' => 202, "data" => "error"]);
//        }
//
//        if (empty($postData['mobile'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'mobile不能为空');
//            return Json(['msg' => 'mobile不能为空', 'status' => 202, "data" => "error"]);
//        }
//
//        $postData['city'] = !empty($postData['city']) ? $postData['city'] : '';
//
////        if(empty($postData['city'])){
////            return Json(['msg'=>'city不能为空','status'=>202,"data"=>"error"]);
////        }
//
//        if (empty($postData['money'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'money不能为空');
//            return Json(['msg' => 'money不能为空', 'status' => 202, "data" => "error"]);
//        }
//
//        if (empty($postData['url'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'url不能为空');
//            return Json(['msg' => 'url不能为空', 'status' => 202, "data" => "error"]);
//        }
//
//
//
//        $params['clue_id'] = time() . mt_rand(1, 999999);
//        $params['adv_id'] = $aid;;
//        $params['clue_name'] = $postData['name'];
//        $params['phone'] = $postData['mobile'];
//        $params['city'] = $postData['city'];
//        $params['apply_limit'] = $postData['money'];
//        $params['site_url'] = $postData['url'];
//        $params['ip'] = isset($postData['ip']) ? $postData['ip'] : get_client_ip();
//        $params['pro_id'] = 5;//综合
//
//
//        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
//        if ($isDayPhone) {
//            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
//            return Json(['msg' => '线索已存在', 'status' => 202, "data" => "error"]);
//        }
//
//
//
////        $formDetail['客户ID']=$postData['customerId'];
////        $formDetail['创建时间']=$postData['createTime'];
//        $formDetail['申请金额'] = $postData['money'];
//        if (!empty($postData['vehicle_brand']) || !empty($postData['purchase']) || !empty($postData['car_age'])) {
//            //车贷
//            $params['pro_id'] = 4;
//            $formDetail['车辆型号'] = isset($postData['vehicle_brand']) ? $postData['vehicle_brand'] : '';
//            $formDetail['购买方式'] = isset($postData['purchase']) ? $postData['purchase'] : '';
//            $formDetail['车辆年限'] = isset($postData['car_age']) ? $postData['car_age'] : '';
//            $params['car'] = '车辆型号：' . $formDetail['车辆型号'] . '|购买方式：' . $formDetail['购买方式'] . '|车辆年限：' . $formDetail['车辆年限'];
//        }
//
//        if (!empty($postData['remark'])) {
//            if (is_array($postData['remark'])) {
//                //综合贷
//                $params['pro_id'] = 5;
//                $formDetail['其他'] = json_encode($postData['remark'], JSON_UNESCAPED_UNICODE);
//            } else {
//                //房贷
//                $params['pro_id'] = 3;
//                $params['house'] = $postData['remark'];
//                $formDetail['其他'] = $postData['remark'];
//            }
//        }
//
//        //公积金
//        if (!empty($postData['size'])) {
//            $params['public_funds'] = $postData['size'];
//            $formDetail['缴纳基数'] = isset($postData['size']) ? $postData['size'] : '';
//            $formDetail['单位属性'] = isset($postData['type']) ? $postData['type'] : '';
//            $params['pro_id'] = 6;
//        }
//
//        //企业贷
//        if (!empty($postData['year'])) {
//            $formDetail['经营年限'] = isset($postData['year']) ? $postData['year'] : '';
//            $formDetail['企业性质'] = isset($postData['type']) ? $postData['type'] : '';
//            $params['pro_id'] = 7;
//        }
//
//        $params['remark'] = json_encode($formDetail, JSON_UNESCAPED_UNICODE);
//
//        $params['type'] = 4;
////        $params['clue_type'] = $params['pro_id'];
//
//        $isAid = Db::name('account')->where('adv_id', $aid)->find();
//        if (empty($isAid)) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
//            ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，账户ID不存在');
//            return Json(['msg' => 'API线索接收失败，账户ID不存在', 'status' => 202, "data" => "error"]);
//        }else{
//            $params['type']=$isAid['channel_id'];
//        }
//        if($isAid['status']!=1){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
//            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
//            return Json(['msg' => '账户已禁用', 'status' => 202, "data" => "error"]);
//        }
//
//        $plan = model('Plan')->where(['token' => $access_token])->find();
//
//        if ($plan) {
//            if ($plan['status'] == 2) {
//                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户方案未启用', $params);
//                ApiClueModel::setClueApiLogError($apiId, '账户方案未启用');
//                return Json(['msg' => 'API线索接收失败，推送账户方案未启用', 'status' => 202, "data" => "error"]);
//            }
//
//        } else {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到方案token', $params);
//            ApiClueModel::setClueApiLogError($apiId, '未匹配到方案token');
//            return Json(['msg' => 'API线索接收失败，账户方案不存在', 'status' => 202, "data" => "error"]);
//        }
//
//        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
//        if ($isBlack) {
//            ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
//            return Json(['status' => 410, 'msg' => '进线失败，黑名单线索', 'data' => 'error']);
//        }
//
//
//        if (strpos($params['city'], '|') !== false) {
//            $city_t = explode('|', $params['city']);
//        } else {
//            $city_t = explode('-', $params['city']);
//        }
//
////        if(strpos($city_t[0], '香港') !== false){
////            $params['city']='香港';
////        }elseif (strpos($city_t[0], '澳门') !== false){
////            $params['city']='澳门';
////        }elseif (strpos($city_t[0], '台湾') !== false){
////            $params['city']='台湾';
////        }else{
////        if (count($city_t) == 3) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 2) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 1) {
////            $params['city'] = $city_t[0];
////        }
//////        }
////        if (strpos($params['city'], '文山') !== false) {
////            $city = '文山';
////        } elseif (strpos($params['city'], '凉山') !== false) {
////            $city = '凉山';
////        } elseif (strpos($params['city'], '甘孜') !== false) {
////            $city = '甘孜';
////        } elseif (strpos($params['city'], '恩施') !== false) {
////            $city = '恩施';
////        } else {
////            $city = str_replace('市', '', $params['city'] ?? '');
////        }
//        $city_info = clue_city_transform($city_t);
////        if(!$city_info){
////            ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'未匹配到城市id',$params);
////            return Json(['msg'=>'API线索接收失败，未匹配到线索城市属性','status'=>202,"data"=>"error"]);
////        }
////        $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
////        $params['city'] = $province['id'].'-'.$city_info['id'];
//
//        if (!$city_info) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
////            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
//            $params['city'] = '';
//            $params['err_msg'] = '未匹配到城市id城市解析失败';
//        } else {
//            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
//            $params['city'] = $province['id'] . '-' . $city_info['id'];
//        }
//
//        //城市是否禁用
//        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
//        if(!empty($isCity)){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
//            //return Json(['msg' => '账户城市已禁用', 'status' => 202, "data" => "error"]);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
//            return Json(['msg' => '线索已存在', 'status' => 202, "data" => "error"]);
//        }
//
//        // 城市是否准入
//        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
//        if ($is_allow === false) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
//            return Json(['msg' => '线索已存在', 'status' => 202, "data" => "error"]);
//        }
//
////        if($access_token==123456){
////            return Json(['status'=>200,'msg'=>'测试线索接收成功','data'=>'success']);
////        }
//
//        //记录线索成本
//        $clueCost = model('ClueAddCost')
//            ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
//            ->where('status', 1)
//            ->find();
//        if (empty($clueCost)) {
//            // 找不到城市就找默认全国城市
//            $clueCost = model('ClueAddCost')
//                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
//                ->where('status', 1)
//                ->find();
//        }
//        if (!empty($clueCost)) {
//            $params['price']=$clueCost['money'];
//            $params['true_price']=$clueCost['money'];
//            $params['xz_price']=$clueCost['money'];
//            $params['xz_true_price']=$clueCost['money'];
//            $params['xz_price2']=$clueCost['money'];
//            $params['xz_true_price2']=$clueCost['money'];
//        }else{
//            $params['price']=$isAid['clue_cost'];
//            $params['true_price']=$isAid['clue_cost'];
//            $params['xz_price']=$isAid['clue_cost'];
//            $params['xz_true_price']=$isAid['clue_cost'];
//            $params['xz_price2']=$isAid['clue_cost'];
//            $params['xz_true_price2']=$isAid['clue_cost'];
//        }
//        $params['account_id']=$isAid['id'];
//        //判断线索重复
//        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
//        // 计划ID
//        if (!empty($postData['url'])) {
//            // 解析URL以获取组成部分
//            $url_info = parse_url($postData['url']);
//            if (!empty($url_info['query'])) { // URL参数
//                // 将查询字符串参数解析到一个数组中
//                parse_str($url_info['query'], $queryParams);
//                if (!empty($queryParams) && !empty($queryParams['promotionid'])) {
//                    $params['promotion_id'] = $queryParams['promotionid'];
//                }
//            }
//        }
//        // 1.记录线索
//        $clueModel = new \app\common\model\Clue();
//        $res = $clueModel->saveData($params);
//        $id = $clueModel->id;
//
//        if ($res['code'] != 1000) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
//            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
//            return Json(['msg' => '线索接收失败', 'status' => 202, "data" => "error"]);
//        }
//        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);
//
//        if ($isClue) {
//            Db::name('clue_err_log')->insert(['type' => 1, 'phone'=>$params['phone'],'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
//        }
//
//        if (empty($params['city'])) {
//            return Json(['status' => 200, 'msg' => '线索接收成功', 'data' => 'success']);
//        }
//
//        if ($access_token == 123456 || strpos($params['clue_name'], '测试') !== false) {
//            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'data' => 'success']);
//        }
//        // 2.推送线索
////        $clue_info = $clueModel->find($id);
////
////        $res = $this->cluePush($clue_info, true);
//
//
//        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
//        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
//        $jobQueueName     = "ExprotClue";
//
//        $jobData = ['id'=>$id];
//
//        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
//
//        return Json(['status' => 200, 'msg' => '线索接收成功', 'data' => 'success']);
////        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE),'data'=>'success']);
//    }

    /* 三方推送过来 */
    public function apiPush()
    {

        $post = file_get_contents("php://input");
//        Log::record(json_encode($post,JSON_UNESCAPED_UNICODE), 'error');
//        Log::record($_GET, 'error');

        $params = json_decode($post, true);

        $insertLog = [
            'api_url' => '三方API',
            'adv_id' => isset($params['adv_id']) ? $params['adv_id'] : '',
            'phone' => isset($params['phone']) ? $params['phone'] : '',
            'name' => isset($params['clue_name']) ? $params['clue_name'] : '',
            'city' => isset($params['city']) ? $params['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
//        $type = $_GET['type'];
        $access_token = $_GET['access_token'];

        $params = json_decode($post, true);

//        $sign=api_get_sign($params,$access_token);
//        dump($sign);die;

        unset($params['id']);

        if (empty($params['adv_id'])) {
            ApiClueModel::setClueApiLogError($apiId, '账号不能为空：adv_id');
            throw new ParamException(['msg' => '账号不能为空：adv_id', 'errorCode' => 40001]);
        }
        if (empty($params['clue_name'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索名称不能为空：clue_name');
            throw new ParamException(['msg' => '线索名称不能为空：clue_name', 'errorCode' => 40001]);
        }

        if (empty($params['clue_id'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索ID不能为空：clue_id');
            throw new ParamException(['msg' => '线索ID不能为空：clue_id', 'errorCode' => 40001]);
        }

        $params['city'] = !empty($params['city']) ? $params['city'] : '';
        if (strpos($params['city'], '|') !== false) {
            $city_t = explode('|', $params['city']);
        } elseif (strpos($params['city'], '-') !== false) {
            $city_t = explode('-', $params['city']);
        } else {
            $city_t = [$params['city']];
        }
//        if (count($city_t) == 3) {
//            $params['city'] = $city_t[1];
//        } elseif (count($city_t) == 2) {
//            $params['city'] = $city_t[1];
//        } elseif (count($city_t) == 1) {
//            $params['city'] = $city_t[0];
//        }

        if (empty($params['phone'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索电话不能为空：phone');
            throw new ParamException(['msg' => '线索电话不能为空：phone', 'errorCode' => 40001]);
        }

        if (empty($params['pro_id'])) {
            ApiClueModel::setClueApiLogError($apiId, '产品ID不能为空：pro_id');
            throw new ParamException(['msg' => '产品ID不能为空：pro_id', 'errorCode' => 40001]);
        }


        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001]);
        }


        $params['ip'] = isset($params['ip']) ? $params['ip'] : get_client_ip();

        $isAid = Db::name('account')->where('adv_id', $params['adv_id'])->find();
        if (empty($isAid)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
            ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，账户ID不存在');
            throw new ParamException(['msg' => 'API线索接收失败，账户ID不存在', 'errorCode' => 40001]);
        }else{
            $params['type']=$isAid['channel_id'];
        }

        if($isAid['status']!=1){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
            throw new ParamException(['msg' => '账户已禁用', 'errorCode' => 40001]);
        }


        $plan = model('Plan')->where(['token' => $access_token])->find();

        if ($plan) {
            if ($plan['status'] == 2) {
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '该token推送方案未启用', $params);
                ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，推送方案未启用');
                throw new ParamException(['msg' => 'API线索接收失败，推送方案未启用', 'errorCode' => 40001]);
            }

            if (isset($params['formDetail']) && !empty($params['formDetail'])) {

//                $params['remark'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);
                $params['formDetail'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);

            }
//            $isSign=api_verify_sign($params,$access_token);
//            if($isSign!==true){
//                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'签名认证失败',$params);
//                throw new ParamException(['msg'=>'API线索接收失败，签名认证失败','errorCode'=>40001]);
//            }

            $isClue = model('clue')->where('clue_id', $params['clue_id'])->find();
            if ($isClue) {
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索ID已存在', $params);
                ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，线索ID已存在');
                throw new ParamException(['msg' => 'API线索接收失败，线索ID已存在', 'errorCode' => 40001]);
            }

            //TODO::判断线索去重
//            $isClue=model('clue')->where('phone',$params['phone'])->find();
//            if($isClue){
//                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'线索电话已存在',$params);
//                throw new ParamException(['msg'=>'API线索接收失败，线索电话已存在','errorCode'=>40001]);
//            }

            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == '男') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == '女') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }
            $params['pro_id'] = 5;//综合
            if (isset($params['formDetail']) && !empty($params['formDetail'])) {
                $params['remark'] = $params['formDetail'];
                $params['formDetail'] = json_decode($params['formDetail'], true);
                $car = [];
                $house = [];
                $public_funds = [];
                $company = [];
                foreach ($params['formDetail'] as $k => $v) {
                    if ($v['name'] == '称呼') {
                        $params['clue_name'] = $v['value'];
                    }

                    if (strpos($v['name'], '城市') !== false) {
                        // 百度广告城市处理
                        $city_t = explode(' ', $v['value']);


//                        if(strpos($city_t[0], '香港') !== false){
//                            $params['city']='香港';
//                        }elseif (strpos($city_t[0], '澳门') !== false){
//                            $params['city']='澳门';
//                        }elseif (strpos($city_t[0], '台湾') !== false){
//                            $params['city']='台湾';
//                        }else{
//                        if (count($city_t) == 3) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 2) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 1) {
//                            $params['city'] = $city_t[0];
//                        }
//                        }
                    }

                    if ($v['name'] == '申请金额') {
                        $params['apply_limit'] = $v['value'];
                    }

                    if (strpos($v['name'], '车') !== false) {
                        $car[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 4;
                    }

                    if (strpos($v['name'], '房') !== false) {
                        $house[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 3;
                    }

                    if (strpos($v['name'], '公积金') !== false) {
                        $public_funds[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 6;
                    }

                    if (strpos($v['name'], '企业') !== false) {
                        $company[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 7;
                    }

                    $params['car'] = implode('|', $car);
                    $params['house'] = implode('|', $house);
                    $params['public_funds'] = implode('|', $public_funds);
                    $params['company'] = implode('|', $company);

                }

            }
//            $params['clue_type']=$params['pro_id'];

        } else {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到方案token', $params);
            ApiClueModel::setClueApiLogError($apiId, '未匹配到方案token');
            throw new ParamException(['msg' => 'API线索接收失败，token对应方案不存在', 'errorCode' => 40001]);
        }

        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
        if ($isBlack) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
            ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
            throw new ParamException(['msg' => '进线失败，黑名单线索', 'errorCode' => 41001]);
        }

//        if (strpos($params['city'], '文山') !== false) {
//            $city = '文山';
//        } elseif (strpos($params['city'], '凉山') !== false) {
//            $city = '凉山';
//        } elseif (strpos($params['city'], '甘孜') !== false) {
//            $city = '甘孜';
//        } elseif (strpos($params['city'], '恩施') !== false) {
//            $city = '恩施';
//        } else {
//            $city = str_replace('市', '', $params['city'] ?? '');
//        }
//        $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
//        if(!$city_info){
//            ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'未匹配到城市id',$params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
//        }
//        $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
//        $params['city'] = $province['id'].'-'.$city_info['id'];

        $city_info = clue_city_transform($city_t);

        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //throw new ParamException(['msg' => '账户城市已禁用', 'errorCode' => 40001]);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001]);
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
        if ($is_allow === false) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001]);
        }

//        if($access_token==123456){
//            return Json(['code'=>200,'msg'=>'测试线索接收成功']);
//        }

        //记录线索成本
        $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price']=$clueCost['money'];
            $params['true_price']=$clueCost['money'];
            $params['xz_price']=$clueCost['money'];
            $params['xz_true_price']=$clueCost['money'];
            $params['xz_price2']=$clueCost['money'];
            $params['xz_true_price2']=$clueCost['money'];
        }else{
            $params['price']=$isAid['clue_cost'];
            $params['true_price']=$isAid['clue_cost'];
            $params['xz_price']=$isAid['clue_cost'];
            $params['xz_true_price']=$isAid['clue_cost'];
            $params['xz_price2']=$isAid['clue_cost'];
            $params['xz_true_price2']=$isAid['clue_cost'];
        }
        $params['account_id']=$isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
        // 计划ID
        if (!empty($params['site_url'])) {
            // 解析URL以获取组成部分
            $url_info = parse_url($params['site_url']);
            if (!empty($url_info['query'])) { // URL参数
                // 将查询字符串参数解析到一个数组中
                parse_str($url_info['query'], $queryParams);
                if (!empty($queryParams) && !empty($queryParams['promotionid'])) {
                    $params['promotion_id'] = $queryParams['promotionid'];
                }
            }
        }
        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            throw new ParamException(['msg' => '线索接收失败', 'errorCode' => 40001]);
        }
        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if ($access_token == 123456 || strpos($params['clue_name'], '测试') !== false) {
            return Json(['code' => 200, 'msg' => '测试线索接收成功']);
        }

        if (empty($params['city'])) {
            return Json(['code' => 200, 'msg' => '线索接收成功']);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['code' => 200, 'msg' => '线索接收成功']);
//        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE)]);
    }


    public function apiPushV2()
    {

        $post = file_get_contents("php://input");
//        Log::record(json_encode($post,JSON_UNESCAPED_UNICODE), 'error');
//        Log::record($_GET, 'error');

        $params = json_decode($post, true);

        $insertLog = [
            'api_url' => '三方API',
            'adv_id' => isset($params['adv_id']) ? $params['adv_id'] : '',
            'phone' => isset($params['phone']) ? $params['phone'] : '',
            'name' => isset($params['clue_name']) ? $params['clue_name'] : '',
            'city' => isset($params['city']) ? $params['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
//        $type = $_GET['type'];
//        $access_token = $_GET['access_token'];

        $params = json_decode($post, true);

//        $sign=api_get_sign($params,$access_token);
//        dump($sign);die;

        unset($params['id']);

        if (empty($params['adv_id'])) {
            ApiClueModel::setClueApiLogError($apiId, 'adv_id不能为空');
            throw new ParamException(['msg' => 'adv_id不能为空', 'errorCode' => 40001]);
        }
        if (empty($params['app_key'])) {
            ApiClueModel::setClueApiLogError($apiId, 'app_key不能为空');
            throw new ParamException(['msg' => 'app_key不能为空', 'errorCode' => 40001]);
        }
        if (empty($params['clue_name'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索名称不能为空：clue_name');
            throw new ParamException(['msg' => '线索名称不能为空：clue_name', 'errorCode' => 40001]);
        }

//        if (empty($params['clue_id'])) {
//            ApiClueModel::setClueApiLogError($apiId, '线索ID不能为空：clue_id');
//            throw new ParamException(['msg' => '线索ID不能为空：clue_id', 'errorCode' => 40001]);
//        }
        $params['clue_id']=time().mt_rand(0,99999);

        $params['city'] = !empty($params['city']) ? $params['city'] : '';
        if (strpos($params['city'], '|') !== false) {
            $city_t = explode('|', $params['city']);
        } elseif (strpos($params['city'], '-') !== false) {
            $city_t = explode('-', $params['city']);
        } else {
            $city_t = [$params['city']];
        }
//        if (count($city_t) == 3) {
//            $params['city'] = $city_t[1];
//        } elseif (count($city_t) == 2) {
//            $params['city'] = $city_t[1];
//        } elseif (count($city_t) == 1) {
//            $params['city'] = $city_t[0];
//        }

        if (empty($params['phone'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索电话不能为空：phone');
            throw new ParamException(['msg' => '线索电话不能为空：phone', 'errorCode' => 40001]);
        }

        if (empty($params['pro_id'])) {
            ApiClueModel::setClueApiLogError($apiId, '产品ID不能为空：pro_id');
            throw new ParamException(['msg' => '产品ID不能为空：pro_id', 'errorCode' => 40001]);
        }


        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001,'code'=>201]);
        }


        $params['ip'] = isset($params['ip']) ? $params['ip'] : get_client_ip();

        $isAid = Db::name('account')->where('adv_id', $params['adv_id'])->find();
        if (empty($isAid)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
            ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，账户ID不存在');
            throw new ParamException(['msg' => 'API线索接收失败，账户ID不存在', 'errorCode' => 40001]);
        }else{
            $params['type']=$isAid['channel_id'];
            if($isAid['app_key']!=$params['app_key']){
                $errMsg='app_key错误';
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $params);
                ApiClueModel::setClueApiLogError($apiId, $errMsg);
                throw new ParamException(['msg' => $errMsg, 'errorCode' => 40001]);
            }
        }

        if($isAid['status']!=1){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
            throw new ParamException(['msg' => '账户已禁用', 'errorCode' => 40001]);
        }



            if (isset($params['formDetail']) && !empty($params['formDetail'])) {

//                $params['remark'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);
                $params['formDetail'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);

            }
//            $isSign=api_verify_sign($params,$access_token);
//            if($isSign!==true){
//                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'签名认证失败',$params);
//                throw new ParamException(['msg'=>'API线索接收失败，签名认证失败','errorCode'=>40001]);
//            }

            $isClue = model('clue')->where('clue_id', $params['clue_id'])->find();
            if ($isClue) {
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索ID已存在', $params);
                ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，线索ID已存在');
                throw new ParamException(['msg' => 'API线索接收失败，线索ID已存在', 'errorCode' => 40001]);
            }

            //TODO::判断线索去重
//            $isClue=model('clue')->where('phone',$params['phone'])->find();
//            if($isClue){
//                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'线索电话已存在',$params);
//                throw new ParamException(['msg'=>'API线索接收失败，线索电话已存在','errorCode'=>40001]);
//            }
        if($isAid['is_check_repeat']==1){
            $isClue=model('clue')->where('phone',$params['phone'])->find();
            if($isClue){
                $errMsg='API撞库：线索已存在';
                ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),$errMsg,$params);
                ApiClueModel::setClueApiLogError($apiId, $errMsg);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>40001,'code'=>201]);
            }
        }

            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == '男') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == '女') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }
            if(isset($params['age'])){
                $params['age']=intval($params['age']);
            }
//            $params['pro_id'] = 5;//综合
            if (isset($params['formDetail']) && !empty($params['formDetail'])) {
                $params['remark'] = $params['formDetail'];
//                $params['formDetail'] = str_replace('\\/', '/', $params['formDetail']);
                $params['formDetail'] = json_decode($params['formDetail'], true);
                if(is_string($params['formDetail'])){
                    $params['formDetail'] = json_decode($params['formDetail'], true);
                }
                $car = [];
                $house = [];
                $public_funds = [];
                $company = [];
//                dump($params['formDetail']);die;
                if(is_string($params['formDetail'])){

                }else{
                    foreach ($params['formDetail'] as $k => $v) {
                        if ($v['name'] == '称呼') {
                            $params['clue_name'] = $v['value'];
                        }

                        if (strpos($v['name'], '城市') !== false) {
                            // 百度广告城市处理
                            $city_t = explode(' ', $v['value']);


//                        if(strpos($city_t[0], '香港') !== false){
//                            $params['city']='香港';
//                        }elseif (strpos($city_t[0], '澳门') !== false){
//                            $params['city']='澳门';
//                        }elseif (strpos($city_t[0], '台湾') !== false){
//                            $params['city']='台湾';
//                        }else{
//                        if (count($city_t) == 3) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 2) {
//                            $params['city'] = $city_t[1];
//                        } elseif (count($city_t) == 1) {
//                            $params['city'] = $city_t[0];
//                        }
//                        }
                        }

//                    if ($v['name'] == '申请金额') {
//                        $params['apply_limit'] = $v['value'];
//                    }

                        if (strpos($v['name'], '车') !== false) {
                            $car[] = $v['name'] . '：' . $v['value'];
                            $params['pro_id'] = 4;
                        }

                        if (strpos($v['name'], '房') !== false) {
                            $house[] = $v['name'] . '：' . $v['value'];
                            $params['pro_id'] = 3;
                        }

                        if (strpos($v['name'], '公积金') !== false) {
                            $public_funds[] = $v['name'] . '：' . $v['value'];
                            $params['pro_id'] = 6;
                        }

                        if (strpos($v['name'], '企业') !== false) {
                            $company[] = $v['name'] . '：' . $v['value'];
                            $params['pro_id'] = 7;
                        }

//                    if($v['name']=='车辆型号'||$v['name']=='车辆购买方式'||$v['name']=='车辆年限'){
//                        $car[]=$v['name'].'：'.$v['value'];
//                    }
                        $params['car'] = implode('|', $car);
                        $params['house'] = implode('|', $house);
                        $params['public_funds'] = implode('|', $public_funds);
                        $params['company'] = implode('|', $company);

                    }
                }


            }
//            $params['clue_type']=$params['pro_id'];



        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
        if ($isBlack) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
            ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
            throw new ParamException(['msg' => '进线失败，黑名单线索', 'errorCode' => 41001]);
        }

//        if (strpos($params['city'], '文山') !== false) {
//            $city = '文山';
//        } elseif (strpos($params['city'], '凉山') !== false) {
//            $city = '凉山';
//        } elseif (strpos($params['city'], '甘孜') !== false) {
//            $city = '甘孜';
//        } elseif (strpos($params['city'], '恩施') !== false) {
//            $city = '恩施';
//        } else {
//            $city = str_replace('市', '', $params['city'] ?? '');
//        }
//        $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
//        if(!$city_info){
//            ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'未匹配到城市id',$params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
//        }
//        $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
//        $params['city'] = $province['id'].'-'.$city_info['id'];

        $city_info = clue_city_transform($city_t);

        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //throw new ParamException(['msg' => '账户城市已禁用', 'errorCode' => 40001]);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001]);
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
        if ($is_allow === false) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁止');
            throw new ParamException(['msg' => '账户城市已禁止', 'errorCode' => 40001]);
        }

//        if($access_token==123456){
//            return Json(['code'=>200,'msg'=>'测试线索接收成功']);
//        }

        //记录线索成本
        $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price']=$clueCost['money'];
            $params['true_price']=$clueCost['money'];
            $params['xz_price']=$clueCost['money'];
            $params['xz_true_price']=$clueCost['money'];
            $params['xz_price2']=$clueCost['money'];
            $params['xz_true_price2']=$clueCost['money'];
        }else{
            $params['price']=$isAid['clue_cost'];
            $params['true_price']=$isAid['clue_cost'];
            $params['xz_price']=$isAid['clue_cost'];
            $params['xz_true_price']=$isAid['clue_cost'];
            $params['xz_price2']=$isAid['clue_cost'];
            $params['xz_true_price2']=$isAid['clue_cost'];
        }
        $params['account_id']=$isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
        // 计划ID
        if (!empty($params['site_url'])) {
            // 解析URL以获取组成部分
            $url_info = parse_url($params['site_url']);
            if (!empty($url_info['query'])) { // URL参数
                // 将查询字符串参数解析到一个数组中
                parse_str($url_info['query'], $queryParams);
                if (!empty($queryParams) && !empty($queryParams['promotionid'])) {
                    $params['promotion_id'] = $queryParams['promotionid'];
                }
            }
        }
        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            throw new ParamException(['msg' => '线索接收失败', 'errorCode' => 40001]);
        }
        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            return Json(['code' => 200, 'msg' => '测试线索接收成功']);
        }

        if (empty($params['city'])) {
            return Json(['code' => 200, 'msg' => '线索接收成功']);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['code' => 200, 'msg' => '线索接收成功']);
//        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE)]);
    }

    /* 接受官方线索 */
    public function accept()
    {

        $post = file_get_contents("php://input");
//        Log::record($post, 'error');
//        Log::record($_GET, 'error');

        $type = $_GET['type'];
//        $access_token = $_GET['access_token'];

        $params = json_decode($post, true);

        $clueName=isset($params['clue_name']) ? $params['clue_name'] : '';
//        if(empty($clueName)&&$type==1){
//            $clueName=isset($params['name']) ? $params['name'] : '';
//        }

        $insertLog = [
            'adv_id' => isset($params['adv_id']) ? $params['adv_id'] : '',
            'phone' => isset($params['phone']) ? $params['phone'] : '',
            'name' => $clueName,
            'city' => isset($params['city']) ? $params['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        if ($type == 1) {
            $apiType = '百度';
//            $insertLog['adv_id'] = isset($params['ucid']) ? $params['ucid'] : '';
        } elseif ($type == 2) {
            $apiType = '腾讯';
//            $insertLog['adv_id'] = isset($params['adv_id']) ? $params['adv_id'] : '';
        } elseif ($type == 3) {
            $apiType = '抖音';
//            $insertLog['adv_id'] = isset($params['adv_id']) ? $params['adv_id'] : '';
        } else {
            $apiType = $type;
        }
        $insertLog['api_url'] = $apiType;
        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);


        unset($params['id']);

        if (!isset($params['clue_id']) || empty($params['clue_id'])) {
            ApiClueModel::setClueApiLogError($apiId, "线索没有ID属性：clue_id");
            throw new ParamException(['msg' => '线索没有ID属性：clue_id', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }
//
//        if(!isset($params['page_id'])){
//            throw new ParamException(['msg'=>'线索没有落地页属性：page_id','errorCode'=>40001]);
//        }
//
        /*if (!isset($params['city']) || empty($params['city'])) {
            throw new ParamException(['msg' => '线索没有城市属性：city', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }*/
//
        if (!isset($params['phone']) || empty($params['phone'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索没有电话属性：phone');
            throw new ParamException(['msg' => '线索没有电话属性：phone', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['type'] = $type;

        $isClue = model('clue')->where('clue_id', $params['clue_id'])->find();
        if ($isClue) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索ID已存在', $params);
            ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，线索ID已存在');
            throw new ParamException(['msg' => 'API线索接收失败，线索ID已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['pro_id'] = 5;//综合

        if(isset($params['page_name'])){
            if (strpos($params['page_name'], '车') !== false) {
                $params['pro_id'] = 4;
            }
            if (strpos($params['page_name'], '房') !== false) {
                $params['pro_id'] = 3;
            }
            if (strpos($params['page_name'], '公积金') !== false) {
                $params['pro_id'] = 6;
            }
            if (strpos($params['page_name'], '企业') !== false) {
                $params['pro_id'] = 7;
            }
        }

        //百度
        if ($type == 1) {

            if (!empty($params['city'])) {
                // 百度广告城市处理
                $city_t = explode(' ', $params['city']);

                $city_info = clue_city_transform($city_t);
                if (!$city_info) {
                    ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到广告城市id', $params);
                    $params['err_msg'] = '未匹配到广告城市id';
                } else {
                    $params['clue_city'] = $city_info['pid'] . '-' . $city_info['id'];
                }
            }

            // 拿到表单里的线索名称
            if (isset($params['formDetail']) && !empty($params['formDetail'])) {

                if (is_string($params['formDetail'])) {
                    $params['formDetail'] = json_decode($params['formDetail'],true);
                }
//                $params['formDetail'] = json_decode($params['formDetail'],true);
//                dump($params);die;
                $params['remark'] = json_encode($params['formDetail'], JSON_UNESCAPED_UNICODE);
                $car = [];
                $house = [];
                $public_funds = [];
                $company = [];
                foreach ($params['formDetail'] as $k => $v) {
                    if ($v['type'] == 'name' || $v['name'] == '称呼') {
                        $params['clue_name'] = $v['value'];
                    }

                    if ($v['type'] == 'city' || $v['name'] == '城市') {

                        // 百度广告城市处理
                        $city_t = explode(' ', $v['value']);

                    }
                    if (!empty($v['city1']) || !empty($v['city2']) || !empty($v['city3'])  || strpos($v['name'], '所在城市') !== false || strpos($v['name'], '所在地') !== false) {
                        // 百度广告城市处理
                        $city_t = explode(' ', $v['value']);

                    }

                    // 性别
                    if ($v['name'] == '性别' && $v['type'] == 'gender') {
                        if ($params['gender'] == '男') {
                            $params['gender'] = 1;
                        } elseif ($params['gender'] == '女') {
                            $params['gender'] = 2;
                        } else {
                            $params['gender'] = 0;
                        }
                    }

                    // 年龄
                    if ($v['name'] == '年龄' && $v['type'] == 'age') {
                        $params['age'] = $v['value'];
                    }

                    if ($v['name'] == '申请金额' || $v['name'] == '申请额度' || $v['name'] == '贷款额度' || $v['name'] == '借款额度' || $v['name'] == '借款金额'||$v['name']=='所需金额' ) {
                        $params['apply_limit'] = $v['value'];
                    }


                    if (strpos($v['name'], '车') !== false) {
                        $car[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 4;
                    }

                    if (strpos($v['name'], '房') !== false) {
                        $house[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 3;
                    }

                    if (strpos($v['name'], '公积金') !== false) {
                        $public_funds[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 6;
                    }

                    if (strpos($v['name'], '企业') !== false) {
                        $company[] = $v['name'] . '：' . $v['value'];
                        $params['pro_id'] = 7;
                    }

                    $params['car'] = implode('|', $car);
                    $params['house'] = implode('|', $house);
                    $params['public_funds'] = implode('|', $public_funds);
                    $params['company'] = implode('|', $company);

                }
            }

            // 根据广告账户名查广告账户id
//            if(!isset($params['adv_name'])){
//                throw new ParamException(['msg'=>'线索没有投广告账户名属性：adv_name','errorCode'=>40001]);
//            }elseif (!empty($params['adv_name'])){
//                $account = Db::name('account')->where('acc_name',$params['adv_name'])->find();
//            }else{
//                $account = Db::name('account')->where('acc_name',$params['ucName'])->find();
//            }
//            if(!$account){
//                throw new ParamException(['msg'=>'投广告账户名未授权','errorCode'=>40002]);
//            }
//            $params['adv_id'] = $account['adv_id'];
//            $params['adv_id'] = $params['ucid'];

        }

        //腾讯
        if ($type == 2) {
            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == 'GENDER_TYPE_MALE') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == 'GENDER_TYPE_FEMALE') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }

            // 线索类型
            if (isset($params['clue_type'])) {
                $clue_types = config('clue.clue_types');
                $params['clue_type'] = $clue_types[$params['clue_type']] ?? '未知';
            }

            // 线索来源
            if (isset($params['source'])) {
                $sources = config('clue.sources');
                $params['source'] = $sources[$params['source']] ?? '未知';
            }
            if (!empty($params['clue_city'])) {
                // 腾讯广告城市处理
                if (strpos($params['clue_city'], '|') !== false) {
                    $clue_city_t = explode('|', $params['clue_city']);
                } else {
                    $clue_city_t = explode('-', $params['clue_city']);
                }
                $clue_city_info = clue_city_transform($clue_city_t);
                if ($clue_city_info) {
                    $params['clue_city'] = $clue_city_info['pid'] . '-' . $clue_city_info['id'];
                    $params['city'] = $clue_city_info['pid'] . '-' . $clue_city_info['id'];
                }
            }

            // 腾讯落地页修改
            if (strpos($params['site_url'], "?")) {
                $params['site_url'] = str_replace(substr($params['site_url'], strpos($params['site_url'], "?")), '', $params['site_url']);
            }

            // 表单内容
            if (isset($params['bundle'])) {
                $car = [];
                $house = [];
                $public_funds = [];
                $company = [];
                $bundle = json_decode($params['bundle'], true);
                unset($bundle['表单名称']);
                $params['remark'] = json_encode($params['bundle'], JSON_UNESCAPED_UNICODE);

                foreach ($bundle as $k => $v) {
                    if ($k == '申请金额' || $k == '申请额度' || $k == '贷款额度' ||$k == '借款额度' || $k == '所需额度'||$k=='需求金额'|| $k == '借款金额') {
                        $params['apply_limit'] = $v;
                    }

                    if (strpos($k, '城市') !== false || $k == 'city') {
                        $params['city'] = $v;
                    }
                    // 腾讯广告城市处理
                    if (strpos($params['city'], '|') !== false) {
                        $city_t = explode('|', $params['city']);
                    } else {
                        $city_t = explode('-', $params['city']);
                    }

                    if (strpos($k, '车') !== false) {
                        $car[] = $k . '：' . $v;
                        $params['pro_id'] = 4;
                    }

                    if (strpos($k, '房') !== false) {
                        $house[] = $k . '：' . $v;
                        $params['pro_id'] = 3;
                    }

                    if (strpos($k, '公积金') !== false) {
                        $public_funds[] = $k . '：' . $v;
                        $params['pro_id'] = 6;
                    }

                    if (strpos($k, '企业') !== false) {
                        $company[] = $k . '：' . $v;
                        $params['pro_id'] = 7;
                    }

                }
                $params['car'] = implode('|', $car);
                $params['house'] = implode('|', $house);
                $params['public_funds'] = implode('|', $public_funds);
                $params['company'] = implode('|', $company);
            }

        }

        //巨量
        if ($type == 3) {

            if (!empty($params['location'])) {
                $city_t = explode('+', $params['location']);

//                if (count($city_t) == 3) {
//                    $params['clue_city'] = $city_t[1];
//                } elseif (count($city_t) == 2) {
//                    $params['clue_city'] = $city_t[1];
//                    if (strpos($params['clue_city'], '区') !== false) {
//                        $params['clue_city'] = $city_t[0];
//                    }
//                } elseif (count($city_t) == 1) {
//                    $params['clue_city'] = $city_t[0];
//                }
//
//                if (strpos($params['clue_city'], '文山') !== false) {
//                    $city = '文山';
//                } elseif (strpos($params['clue_city'], '凉山') !== false) {
//                    $city = '凉山';
//                } elseif (strpos($params['clue_city'], '甘孜') !== false) {
//                    $city = '甘孜';
//                } elseif (strpos($params['clue_city'], '恩施') !== false) {
//                    $city = '恩施';
//                } else {
//                    $city = str_replace('市', '', $params['clue_city'] ?? '');
//                }
//                $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
                $city_info = clue_city_transform($city_t);
                if (!$city_info) {
                    ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到广告城市id', $params);
                    $params['err_msg'] = '未匹配到广告城市id';
                } else {
                    $params['clue_city'] = $city_info['pid'] . '-' . $city_info['id'];
                }
            }

            $city_t=[$params['city']];

            // 性别
            if (isset($params['gender'])) {
                if ($params['gender'] == '男') {
                    $params['gender'] = 1;
                } elseif ($params['gender'] == '女') {
                    $params['gender'] = 2;
                } else {
                    $params['gender'] = 0;
                }
            }

            // 橙子建战落地页修改
//            if(strpos($params['site_url'],"&q=")){
//                $params['site_url'] = str_replace(substr($params['site_url'], strpos($params['site_url'],"&q=")), '', $params['site_url']);
//            }
            $params['page_id']=$params['site_id'];

            // 表单内容
            $params['pro_id'] = 5;
            if (isset($params['remark_dict'])) {
                $car = [];
                $house = [];
                $public_funds = [];
                $company = [];
                foreach ($params['remark_dict'] as $k => $v) {

                    if ($k == '申请金额' || $k == '申请额度' || $k == '贷款额度' || $k=='借款额度'|| $k == '所需额度'||$k=='需求金额'|| $k == '借款金额') {
                        $params['apply_limit'] = $v;
                    }

                    if (strpos($k, '车') !== false) {
                        $car[] = $k . '：' . $v;
                        $params['pro_id'] = 4;
                    }

                    if (strpos($k, '房') !== false) {
                        $house[] = $k . '：' . $v;
                        $params['pro_id'] = 3;
                    }

                    if (strpos($k, '公积金') !== false) {
                        $public_funds[] = $k . '：' . $v;
                        $params['pro_id'] = 6;
                    }

                    if (strpos($k, '企业') !== false) {
                        $company[] = $k . '：' . $v;
                        $params['pro_id'] = 7;
                    }

                }
                $params['remark'] = json_encode($params['remark_dict'], JSON_UNESCAPED_UNICODE);
                $params['car'] = implode('|', $car);
                $params['house'] = implode('|', $house);
                $params['public_funds'] = implode('|', $public_funds);
                $params['company'] = implode('|', $company);
            }

        }



        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }

        $params['ip'] = isset($params['ip']) ? $params['ip'] : get_client_ip();
//        if (strpos($params['city'], '文山') !== false) {
//            $city = '文山';
//        } elseif (strpos($params['city'], '凉山') !== false) {
//            $city = '凉山';
//        } elseif (strpos($params['city'], '甘孜') !== false) {
//            $city = '甘孜';
//        } elseif (strpos($params['city'], '恩施') !== false) {
//            $city = '恩施';
//        } else {
//            $city = str_replace('市', '', $params['city'] ?? '');
//        }
//        $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
        if(empty($city_t)){
            $city_t=[];
        }
        $city_info = clue_city_transform($city_t);
        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //记录线索成本
        $isAid = Db::name('account')->where('adv_id', $params['adv_id'])->find();

        //城市是否禁用
        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
        if(!empty($isCity)){
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //throw new ParamException(['msg' => '账户城市已禁用', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            throw new ParamException(['msg' => '线索已存在', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }


        if(!empty($isAid)){
            if($isAid['status']!=1){
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
                ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
                throw new ParamException(['msg' => '账户已禁用', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
            }

            $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
                ->where('status', 1)
                ->find();
            if (empty($clueCost)) {
                // 找不到城市就找默认全国城市
                $clueCost = model('ClueAddCost')
                    ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                    ->where('status', 1)
                    ->find();
            }
            if (!empty($clueCost)) {
                $params['price']=$clueCost['money'];
                $params['true_price']=$clueCost['money'];
                $params['xz_price']=$clueCost['money'];
                $params['xz_true_price']=$clueCost['money'];
                $params['xz_price2']=$clueCost['money'];
                $params['xz_true_price2']=$clueCost['money'];
            }else{
                $params['price']=$isAid['clue_cost'];
                $params['true_price']=$isAid['clue_cost'];
                $params['xz_price']=$isAid['clue_cost'];
                $params['xz_true_price']=$isAid['clue_cost'];
                $params['xz_price2']=$isAid['clue_cost'];
                $params['xz_true_price2']=$isAid['clue_cost'];
            }
            $params['account_id']=$isAid['id'];
        }

        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            throw new ParamException(['msg' => '线索接收失败', 'errorCode' => 40001, 'code' => 400, 'message' => 'error']);
        }
        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            return Json(['code' => 200, 'msg' => '测试线索接收成功' . json_encode($res, JSON_UNESCAPED_UNICODE), 'message' => 'success']);
        }

        if (empty($params['city'])&&empty($params['clue_city'])) {
            return Json(['code' => 200, 'msg' => '线索接收成功,城市匹配失败：' . json_encode($res, JSON_UNESCAPED_UNICODE), 'message' => 'success']);
        }

        if (empty($isAid)) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收成功,投放账户未设置', $post);
            return Json(['code' => 200, 'msg' => '线索接收成功,投放账户未设置：' . json_encode($res, JSON_UNESCAPED_UNICODE), 'message' => 'success']);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName     = "ExprotClue";

        $jobData = ['id'=>$id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['code' => 200, 'msg' => '线索接收成功', 'message' => 'success']);
    }

    //上海目标
//    public function shanghaiPush()
//    {
//
//        $post = file_get_contents("php://input");
////        Log::record($post, 'error');
////        Log::record($_GET, 'error');
//
//        $postData = json_decode($post, true);
//
//        $aid = 9523;
//        $insertLog = [
//            'api_url' => '上海目标',
//            'adv_id' => $aid,
//            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
//            'name' => isset($postData['username']) ? $postData['username'] : '',
//            'city' => isset($postData['city']) ? $postData['city'] : '',
//            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
//            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
//            'create_time' => date('Y-m-d H:i:s')
//        ];
//        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
//
//        if (empty($postData['username'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'username不能为空');
//            return Json(['msg' => 'username不能为空', 'status' => 200, "code" => 500]);
//        }
//
//        if (empty($postData['mobile'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'mobile不能为空');
//            return Json(['msg' => 'mobile不能为空',  'status' => 200, "code" => 500]);
//        }
//
//        if(empty($postData['city'])){
//            ApiClueModel::setClueApiLogError($apiId, 'city不能为空');
//            return Json(['msg'=>'city不能为空', 'status' => 200, "code" => 500]);
//        }
//
//        if (empty($postData['remark'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'remark不能为空');
//            return Json(['msg' => 'remark不能为空',  'status' => 200, "code" => 500]);
//        }
//
//        if(empty($postData['type'])){
//            $pro_id=5;
//        }else{
//            if($postData['type']==1){
//                $pro_id=4;
//            }elseif ($postData['type']==2){
//                $pro_id=3;
//            }
//        }
//
//        $params['clue_id'] = time() . mt_rand(1, 999999);
//        $params['adv_id'] = $aid;;
//        $params['clue_name'] = $postData['username'];
//        $params['phone'] = $postData['mobile'];
//        $params['city'] = $postData['city'];
//        $params['apply_limit'] = isset($postData['quota'])?$postData['quota']:0;
//        $params['age'] = isset($postData['age'])?$postData['age']:0;
//        $params['gender'] = isset($postData['sex'])?$postData['sex']:0;
//        $params['pro_id'] = $pro_id;
//        $params['ip'] = isset($postData['ip']) ? $postData['ip'] : get_client_ip();
//
////        $params['remark'] = isset($postData['remark']) ? $postData['remark'] : '';
//
//        $params['house'] = isset($postData['house']) ? $postData['house'] : '';
//        $params['car'] = isset($postData['car']) ? $postData['car'] : '';
//        $params['credit'] = isset($postData['credit']) ? $postData['credit'] : '';
//
//        $remark[]=isset($postData['remark']) ? $postData['remark'] : '';
//        if(!empty($params['car'])){
//            $remark[]=$params['car'];
//        }
//        if(!empty($params['house'])){
//            $remark[]=$params['house'];
//        }
//        $params['remark']=json_encode($remark,JSON_UNESCAPED_UNICODE);
//
//
//        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
//        if ($isDayPhone) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
//            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//
//        $isAid = Db::name('account')->where('adv_id', $aid)->find();
//        if($isAid['status']!=1){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
//            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
//            return Json(['msg' => '账户已禁用',  'status' => 200, "code" => 500]);
//        }
//        $params['type']=$isAid['channel_id'];
////        $isAid = Db::name('account')->where('adv_id', $aid)->find();
////        if (empty($isAid)) {
////            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
////            return Json(['msg' => 'API线索接收失败，账户ID不存在', 'status' => 202, "data" => "error"]);
////        }
//
//        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
//        if ($isBlack) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
//            ApiClueModel::setClueApiLogError($apiId, '进线失败，黑名单线索');
//            return Json(['msg' => '进线失败，黑名单线索',  'status' => 200, "code" => 500]);
//        }
//
//
//        if (strpos($params['city'], '|') !== false) {
//            $city_t = explode('|', $params['city']);
//        } elseif(strpos($params['city'], '-') !== false) {
//            $city_t = explode('-', $params['city']);
//        }else{
//            $city_t=[$params['city']];
//        }
//
////        if(strpos($city_t[0], '香港') !== false){
////            $params['city']='香港';
////        }elseif (strpos($city_t[0], '澳门') !== false){
////            $params['city']='澳门';
////        }elseif (strpos($city_t[0], '台湾') !== false){
////            $params['city']='台湾';
////        }else{
////        if (count($city_t) == 3) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 2) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 1) {
////            $params['city'] = $city_t[0];
////        }
//////        }
////        if (strpos($params['city'], '文山') !== false) {
////            $city = '文山';
////        } elseif (strpos($params['city'], '凉山') !== false) {
////            $city = '凉山';
////        } elseif (strpos($params['city'], '甘孜') !== false) {
////            $city = '甘孜';
////        } elseif (strpos($params['city'], '恩施') !== false) {
////            $city = '恩施';
////        } else {
////            $city = str_replace('市', '', $params['city'] ?? '');
////        }
//        $city_info = clue_city_transform($city_t);
////        if(!$city_info){
////            ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'未匹配到城市id',$params);
////            return Json(['msg'=>'API线索接收失败，未匹配到线索城市属性','status'=>202,"data"=>"error"]);
////        }
////        $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
////        $params['city'] = $province['id'].'-'.$city_info['id'];
//
//        if (!$city_info) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
////            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
//            $params['city'] = '';
//            $params['err_msg'] = '未匹配到城市id城市解析失败';
//        } else {
//            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
//            $params['city'] = $province['id'] . '-' . $city_info['id'];
//        }
//
//        //城市是否禁用
//        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
//        if(!empty($isCity)){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
//            //return Json(['msg' => '账户城市已禁用',  'status' => 200, "code" => 500]);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//        // 城市是否准入
//        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
//        if ($is_allow === false) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//        $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
//            ->where('status', 1)
//            ->find();
//        if (empty($clueCost)) {
//            // 找不到城市就找默认全国城市
//            $clueCost = model('ClueAddCost')
//                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
//                ->where('status', 1)
//                ->find();
//        }
//        if (!empty($clueCost)) {
//            $params['price']=$clueCost['money'];
//            $params['true_price']=$clueCost['money'];
//            $params['xz_price']=$clueCost['money'];
//            $params['xz_true_price']=$clueCost['money'];
//            $params['xz_price2']=$clueCost['money'];
//            $params['xz_true_price2']=$clueCost['money'];
//        }else{
//            $params['price']=$isAid['clue_cost'];
//            $params['true_price']=$isAid['clue_cost'];
//            $params['xz_price']=$isAid['clue_cost'];
//            $params['xz_true_price']=$isAid['clue_cost'];
//            $params['xz_price2']=$isAid['clue_cost'];
//            $params['xz_true_price2']=$isAid['clue_cost'];
//        }
//        $params['account_id']=$isAid['id'];
//        //判断线索重复
//        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
//        if($isClue){
//            ApiClueModel::setClueApiLogError($apiId, '线索手机重复');
//            return Json(['status' => 200, 'msg' => '线索手机重复', 'code' => 202]);
//        }
//        // 1.记录线索
//        $clueModel = new \app\common\model\Clue();
//        $res = $clueModel->saveData($params);
//        $id = $clueModel->id;
//
//        if ($res['code'] != 1000) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
//            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
//            return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
//        }
//
//        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);
//
//        if ($isClue) {
//            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
//        }
//
//        if (empty($params['city'])) {
//            return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
//        }
//
//        if (strpos($params['clue_name'], '测试') !== false) {
//            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 200]);
//        }
//
//        // 2.推送线索
////        $clue_info = $clueModel->find($id);
////
////        $res = $this->cluePush($clue_info, true);
//
//        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
//        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
//        $jobQueueName     = "ExprotClue";
//
//        $jobData = ['id'=>$id];
//
//        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
//
//        return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
////        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE),'data'=>'success']);
//    }

    //抖音上海目标
//    public function shanghaiPush2()
//    {
//
//        $post = file_get_contents("php://input");
////        Log::record($post, 'error');
////        Log::record($_GET, 'error');
//
//        $postData = json_decode($post, true);
//
//        $aid = 9521;
//        $insertLog = [
//            'api_url' => '上海目标',
//            'adv_id' => $aid,
//            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
//            'name' => isset($postData['username']) ? $postData['username'] : '',
//            'city' => isset($postData['city']) ? $postData['city'] : '',
//            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
//            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
//            'create_time' => date('Y-m-d H:i:s')
//        ];
//        $apiId=Db::name('clue_api_log')->insertGetId($insertLog);
//
//        if (empty($postData['username'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'username不能为空');
//            return Json(['msg' => 'username不能为空', 'status' => 200, "code" => 500]);
//        }
//
//        if (empty($postData['mobile'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'mobile不能为空');
//            return Json(['msg' => 'mobile不能为空',  'status' => 200, "code" => 500]);
//        }
//
//        if(empty($postData['city'])){
//            ApiClueModel::setClueApiLogError($apiId, 'city不能为空');
//            return Json(['msg'=>'city不能为空', 'status' => 200, "code" => 500]);
//        }
//
//        if (empty($postData['remark'])) {
//            ApiClueModel::setClueApiLogError($apiId, 'remark不能为空');
//            return Json(['msg' => 'remark不能为空',  'status' => 200, "code" => 500]);
//        }
//
//        if(empty($postData['type'])){
//            $pro_id=5;
//        }else{
//            if($postData['type']==1){
//                $pro_id=4;
//            }elseif ($postData['type']==2){
//                $pro_id=3;
//            }
//        }
//
//        $params['clue_id'] = time() . mt_rand(1, 999999);
//        $params['adv_id'] = $aid;;
//        $params['clue_name'] = $postData['username'];
//        $params['phone'] = $postData['mobile'];
//        $params['city'] = $postData['city'];
//        $params['apply_limit'] = isset($postData['quota'])?$postData['quota']:0;
//        $params['age'] = isset($postData['age'])?$postData['age']:0;
//        $params['gender'] = isset($postData['sex'])?$postData['sex']:0;
//        $params['pro_id'] = $pro_id;
//        $params['ip'] = isset($postData['ip']) ? $postData['ip'] : get_client_ip();
//
////        $params['remark'] = isset($postData['remark']) ? $postData['remark'] : '';
//
//        $params['house'] = isset($postData['house']) ? $postData['house'] : '';
//        $params['car'] = isset($postData['car']) ? $postData['car'] : '';
//        $params['credit'] = isset($postData['credit']) ? $postData['credit'] : '';
//
//        $remark[]=isset($postData['remark']) ? $postData['remark'] : '';
//        if(!empty($params['car'])){
//            $remark[]=$params['car'];
//        }
//        if(!empty($params['house'])){
//            $remark[]=$params['house'];
//        }
//        $params['remark']=json_encode($remark,JSON_UNESCAPED_UNICODE);
//
//        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
//        if ($isDayPhone) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
//            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//        $isAid = Db::name('account')->where('adv_id', $aid)->find();
//        if($isAid['status']!=1){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
//            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
//            return Json(['msg' => '账户已禁用',  'status' => 200, "code" => 500]);
//        }
//
//        $isBlack = model('clue')->where(['phone' => $params['phone'],'is_black'=>1])->find();
//        if ($isBlack) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
//            ApiClueModel::setClueApiLogError($apiId, '进线失败，黑名单线索');
//            return Json(['msg' => '进线失败，黑名单线索',  'status' => 200, "code" => 500]);
//        }
//
//        $params['type']=$isAid['channel_id'];
////        if (empty($isAid)) {
////            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户ID错误', $params);
////            return Json(['msg' => 'API线索接收失败，账户ID不存在', 'status' => 202, "data" => "error"]);
////        }
//
//
//        if (strpos($params['city'], '|') !== false) {
//            $city_t = explode('|', $params['city']);
//        } elseif(strpos($params['city'], '-') !== false) {
//            $city_t = explode('-', $params['city']);
//        }else{
//            $city_t=[$params['city']];
//        }
//
////        if(strpos($city_t[0], '香港') !== false){
////            $params['city']='香港';
////        }elseif (strpos($city_t[0], '澳门') !== false){
////            $params['city']='澳门';
////        }elseif (strpos($city_t[0], '台湾') !== false){
////            $params['city']='台湾';
////        }else{
////        if (count($city_t) == 3) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 2) {
////            $params['city'] = $city_t[1];
////        } elseif (count($city_t) == 1) {
////            $params['city'] = $city_t[0];
////        }
//////        }
////        if (strpos($params['city'], '文山') !== false) {
////            $city = '文山';
////        } elseif (strpos($params['city'], '凉山') !== false) {
////            $city = '凉山';
////        } elseif (strpos($params['city'], '甘孜') !== false) {
////            $city = '甘孜';
////        } elseif (strpos($params['city'], '恩施') !== false) {
////            $city = '恩施';
////        } else {
////            $city = str_replace('市', '', $params['city'] ?? '');
////        }
//        $city_info = clue_city_transform($city_t);
////        if(!$city_info){
////            ClueErrorLog::record($params['clue_id'] ?? time().mt_rand(1000,9999),'未匹配到城市id',$params);
////            return Json(['msg'=>'API线索接收失败，未匹配到线索城市属性','status'=>202,"data"=>"error"]);
////        }
////        $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
////        $params['city'] = $province['id'].'-'.$city_info['id'];
//
//        if (!$city_info) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
////            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
//            $params['city'] = '';
//            $params['err_msg'] = '未匹配到城市id城市解析失败';
//        } else {
//            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
//            $params['city'] = $province['id'] . '-' . $city_info['id'];
//        }
//
//        //城市是否禁用
//        $isCity=model('accountCity')->where(['acc_id'=>$isAid['id'],'city'=>$params['city'],'status'=>1])->find();
//        if(!empty($isCity)){
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
//            //return Json(['msg' => '账户城市已禁用',  'status' => 200, "code" => 500]);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//        // 城市是否准入
//        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
//        if ($is_allow === false) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
//            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
//            return Json(['msg' => '线索已存在',  'status' => 200, "code" => 500]);
//        }
//
//        $clueCost = model('ClueAddCost')->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
//            ->where('status', 1)
//            ->find();
//        if (empty($clueCost)) {
//            // 找不到城市就找默认全国城市
//            $clueCost = model('ClueAddCost')
//                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
//                ->where('status', 1)
//                ->find();
//        }
//        if (!empty($clueCost)) {
//            $params['price']=$clueCost['money'];
//            $params['true_price']=$clueCost['money'];
//            $params['xz_price']=$clueCost['money'];
//            $params['xz_true_price']=$clueCost['money'];
//            $params['xz_price2']=$clueCost['money'];
//            $params['xz_true_price2']=$clueCost['money'];
//        }else{
//            $params['price']=$isAid['clue_cost'];
//            $params['true_price']=$isAid['clue_cost'];
//            $params['xz_price']=$isAid['clue_cost'];
//            $params['xz_true_price']=$isAid['clue_cost'];
//            $params['xz_price2']=$isAid['clue_cost'];
//            $params['xz_true_price2']=$isAid['clue_cost'];
//        }
//        $params['account_id']=$isAid['id'];
//        //判断线索重复
//        $isClue = model('clue')->where(['phone' => $params['phone']])->find();
//        if($isClue){
//            ApiClueModel::setClueApiLogError($apiId, '线索手机重复');
//            return Json(['status' => 200, 'msg' => '线索手机重复', 'code' => 202]);
//        }
//
//        // 1.记录线索
//        $clueModel = new \app\common\model\Clue();
//        $res = $clueModel->saveData($params);
//        $id = $clueModel->id;
//
//        if ($res['code'] != 1000) {
//            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
//            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
//            return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
//        }
//
//        Db::name('clue_api_log')->where('id',$apiId)->update(['status'=>1]);
//
//        if ($isClue) {
//            Db::name('clue_err_log')->insert(['type' => 1,'phone'=>$params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
//        }
//
//        if (empty($params['city'])) {
//            return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
//        }
//
//        if (strpos($params['clue_name'], '测试') !== false) {
//            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 200]);
//        }
//
//        // 2.推送线索
////        $clue_info = $clueModel->find($id);
////
////        $res = $this->cluePush($clue_info, true);
//
//        $jobHandlerClassName  = 'app\job\ExprotClue@fire';
//        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
//        $jobQueueName     = "ExprotClue";
//
//        $jobData = ['id'=>$id];
//
//        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
//
//        return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
////        return Json(['code'=>200,'msg'=>'线索接收成功：'.json_encode($res,JSON_UNESCAPED_UNICODE),'data'=>'success']);
//    }


    /* 线索分发 */
    public function cluePush($clue_info, $isFirst = false,$listPush=[])
    {

//        dump($clue_info);
        if (strpos($clue_info['clue_name'], '测试') !== false) {
            return ['code' => 400, 'msg' => '测试线索不能推送！'];
        }
        // 1.读取线索规则
        $push = $this->getPushRule($clue_info, 0, $isFirst,$listPush);
        if ($push['code'] == 0) {
            if ($isFirst&&request()->domain()!=config('testdomain')) {
                $accInfo=Db::name('account')->where('id',$clue_info['account_id'])->find();
                $qudao=$accInfo['acc_name'];
                $smsCity='';
                if($clue_info['city'] != ''){
                    $ids = explode('-',$clue_info['city']);
                    $cityNum=count($ids);
                    if($cityNum==1){
                        $smsCity = $this->getCityName($ids[0]);
                    }elseif ($cityNum==2){
                        $prov = $this->getCityName($ids[0]);
                        $city = $this->getCityName($ids[1]);
                        if($prov == $city){
                            $smsCity = $prov;
                        }else{
                            $smsCity = $prov.'-'.$city;
                        }
                    }
                }

                $errMsg=Db::name('clue')->where('id',$clue_info['id'])->value('err_msg');
                if(empty($errMsg)){
                    $errMsg=$push['msg'];
                }

                $mobiles=Db::name('admin')->where('id',6)->value('tel');
                $content='【'.config('database')['host_sms_name'].'】产生未推送线索，渠道：'.$qudao.'，城市：'.$smsCity.'，失败原因：'.$errMsg;
                $extno='';
                $sendtime='';
//                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '线索没有可分发的商户', $push);
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
                //优化师发消息
                if(!empty($accInfo['bind_youhua'])){
                    $youhuaPhone=Db::name('admin')->where('id',$accInfo['bind_youhua'])->value('tel');
                    if(!empty($youhuaPhone)&&strlen($youhuaPhone)==11){
                        $sendRes=SmsMuSend::send($youhuaPhone,$content);
                    }
                }

            }else{
//                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '线索没有可分发的商户', $push);
            }

            // 更新手机归属地城市
            $mobile_city = (new ApiClueModel())->getMobileCity($clue_info['phone']);
            if ($mobile_city !== false) {
                \db('clue')->where('id', $clue_info['id'])->update(['mobile_city' => $mobile_city]);
            }

            return ['code' => 400, 'msg' => $push['msg']];
        } else {
            $pushInfo = $push['data'];
//            dump($pushInfo);
        }
//        dump($clue_info);
////        dump($push);
////        dump($push);
//        dump('最终推送给');
//        dump($pushInfo);
//        die;
        if ($pushInfo) {
            $clue_info['city']=$pushInfo['city'];
            // 2.根据商户api地址做推送
            $res = $this->sendMerchantClue($pushInfo, $clue_info,0,$listPush);
            if ($res === true) {
                $merchant = Db::name('merchant')->where('id', $pushInfo['mer_id'])->find();
                //子商户推送
                if($merchant['is_sub_mer']==1){
                    // 1.当前任务将由哪个类来负责处理。
                    // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                    $jobHandlerClassName  = 'app\job\SubCluePush@fire';
                    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                    $jobQueueName     = "SubCluePush";

                    $jobData = ['mer_id'=>$merchant['id'],'clue_id'=>$clue_info['id']];
                    $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                }
                //推送成功发送短信
                $sendPhone=$merchant['phone'];
                if ($merchant['is_send_phone']==1&&$sendPhone&&request()->domain()!=config('testdomain')) {
                    $mobiles = $sendPhone;
                    $content='【'.config('database')['host_sms_name']."】提醒你有个线索查看！";
                    $extno = '';
                    $sendtime = '';
//                    $sendRes = MessageSend::send($mobiles, $extno, $content, $sendtime);
//                    $result = json_decode(json_encode(simplexml_load_string($sendRes, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//                    $result['clue_info']=$clue_info['clue_id'];
//                    $result['mer_phone']=$sendPhone;
//                    trace($result, 'error');
                    $sendRes=SmsMuSend::send($mobiles,$content);
                }
                return ['code' => 200, 'msg' => '线索推送成功'];
            } else {
                return ['code' => 400, 'msg' => $res];
            }
        } else {
            if ($isFirst&&request()->domain()!=config('testdomain')) {
                $accInfo=Db::name('account')->where('id',$clue_info['account_id'])->find();
                $qudao=$accInfo['acc_name'];
                $smsCity='';
                if($clue_info['city'] != ''){
                    $ids = explode('-',$clue_info['city']);
                    $cityNum=count($ids);
                    if($cityNum==1){
                        $smsCity = $this->getCityName($ids[0]);
                    }elseif ($cityNum==2){
                        $prov = $this->getCityName($ids[0]);
                        $city = $this->getCityName($ids[1]);
                        if($prov == $city){
                            $smsCity = $prov;
                        }else{
                            $smsCity = $prov.'-'.$city;
                        }
                    }
                }

                $errMsg=Db::name('clue')->where('id',$clue_info['id'])->value('err_msg');
                if(empty($errMsg)){
                    $errMsg='没有可分发的商户';
                }

                $mobiles=Db::name('admin')->where('id',6)->value('tel');
                $content='【'.config('database')['host_sms_name'].'】产生未推送线索，渠道：'.$qudao.'，城市：'.$smsCity.'，失败原因：'.$errMsg;
                $extno='';
                $sendtime='';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '线索没有可分发的商户', $clue_info);
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);

                //优化师发消息
                if(!empty($accInfo['bind_youhua'])){
                    $youhuaPhone=Db::name('admin')->where('id',$accInfo['bind_youhua'])->value('tel');
                    if(!empty($youhuaPhone)&&strlen($youhuaPhone)==11){
                        $sendRes=SmsMuSend::send($youhuaPhone,$content);
                    }
                }

            }else{
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '线索没有可分发的商户', $clue_info);
            }

            // 更新手机归属地城市
            $mobile_city = (new ApiClueModel())->getMobileCity($clue_info['phone']);
            if ($mobile_city !== false) {
                \db('clue')->where('id', $clue_info['id'])->update(['mobile_city' => $mobile_city]);
            }

            return ['code' => 400, 'msg' => '线索没有可分发的商户'];
        }

    }

    // 读取线索规则，找出需要推送的那个商户
    public function getPushRule($clue_info, $nextCity = 0, $isFirst = false,$listPush=[])
    {
        $push = [];
            $pro_id = $clue_info['pro_id'];

                // 1.根据线索的落地页查找线索绑定的产品
            $page = model('Page')->where(['page_id' => $clue_info['page_id']])->find();

            if ($page) {
                if (empty($page['pro_id'])) {
                    $errMsg = '落地页未关联产品';
                    ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $page);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                    if ($isFirst) {
                        Db::name('clue_err_log')->insert(['type' => 3, 'clue_id' => $clue_info['id'], 'adv_id' => $clue_info['adv_id'], 'pro_id' => $pro_id, 'city' => $clue_info['city'], 'create_time' => time()]);
                    }
                    Db::name('admin_clue_mer')->insert(['clue_id'=>$clue_info['id'],'mer_id'=>0]);
                    return ['code' => 0, 'msg' => $errMsg];
                } else {
                    $pro_id = $page['pro_id'];
                    if ($pro_id != $clue_info['pro_id']) {
                        $errMsg = '落地页关联产品与线索识别产品不匹配';
                        ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $page);
                        model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                        if ($isFirst) {
                            Db::name('clue_err_log')->insert(['type' => 3, 'clue_id' => $clue_info['id'], 'adv_id' => $clue_info['adv_id'], 'pro_id' => $pro_id, 'city' => $clue_info['city'], 'create_time' => time()]);
                        }
                        Db::name('admin_clue_mer')->insert(['clue_id'=>$clue_info['id'],'mer_id'=>0]);
                        return ['code' => 0, 'msg' => $errMsg];
                    }
                }
            } else {
                $errMsg = '未匹配到落地页ID';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $clue_info);
            }

            //特定账户落地页分发给特定商户
            if($page['page_id']==9999999){
                $pushs = model('Push')->getListByMap(['id' => 999999999]);
            }else{
                $pushs = model('Push')->getListByMap(['pro_id' => $pro_id, 'city' => $clue_info['city']]);
            }

        if (!$pushs) {
            $errMsg = '根据产品和城市未找到分发规则';
            ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $clue_info);
            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
            if ($isFirst) {
                Db::name('clue_err_log')->insert(['type' => 3, 'clue_id' => $clue_info['id'], 'adv_id' => $clue_info['adv_id'], 'pro_id' => $pro_id, 'city' => $clue_info['city'], 'create_time' => time()]);
            }
//            return ['code' => 0, 'msg' => $errMsg];
            //如果有广告城市
            if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
//                if($clue_info['type']==1){
//                    return ['code' => 0, 'msg' => $errMsg];
//                }
                $clue_info['city'] = $clue_info['clue_city'];
                $clue_info['next_city'] = $clue_info['clue_city'];
                return $this->getPushRule($clue_info, 1, false);
            } else {
                Db::name('admin_clue_mer')->insert(['clue_id'=>$clue_info['id'],'mer_id'=>0]);
                return ['code' => 0, 'msg' => $errMsg];
            }
        } else {
            $pushInfo = $pushs;
            //筛选渠道
            foreach ($pushs as $k => $v) {
                $merArrLog[]=['clue_id'=>$clue_info['id'],'mer_id'=>$v['mer_id'],'push_id'=>$v['id']];
                $isC=false;
                foreach ($listPush as $vv){
                    if($v['id']==$vv){
                        unset($pushs[$k]);
                        $isC=true;
                    }
                }
                if($isC){
                    continue;
                }
                $date = date('Y-m-d H:i:s');
                $times = explode(' - ', $v['timing_time']);
                if ($date > $times[0] && $date < $times[1]) {
                    if(!empty($v['week_time'])){
                        $weekArr=json_decode($v['week_time'],true);
                        //全部星期
                        if(empty($weekArr)){

                        }else{
                            if(isset($weekArr[10])){

                                if(empty($weekArr[10])){

                                }else{
                                    $timeDay=explode(' - ',$weekArr[10]);
                                    $stime=strtotime(date('Y-m-d '.$timeDay[0]));
                                    $etime=strtotime(date('Y-m-d '.$timeDay[1]));
                                    if(time()>$stime&&time()<$etime){

                                    }else{
                                        unset($pushs[$k]);
                                    }
                                }
                            }else{
                                $nowWeek=date('w');
                                if(isset($weekArr[$nowWeek])){
                                    if(empty($weekArr[$nowWeek])){

                                    }else{
                                        $timeDay=explode(' - ',$weekArr[$nowWeek]);
                                        $stime=strtotime(date('Y-m-d '.$timeDay[0]));
                                        $etime=strtotime(date('Y-m-d '.$timeDay[1]));
                                        if(time()>$stime&&time()<$etime){

                                        }else{
                                            unset($pushs[$k]);
                                        }
                                    }
                                }else{
                                    unset($pushs[$k]);
                                }
                            }
                        }
                    }
                }else{
                    unset($pushs[$k]);
                }
            }

            if(!empty($merArrLog)){
                Db::name('admin_clue_mer')->insertAll($merArrLog);
            }

            if (empty($pushs)) {
                // 都超过了每日接收上限
                $errMsg = '没有符合时间日期的规则';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $pushInfo);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
//                if ($isFirst) {
//                    Db::name('clue_err_log')->insert(['type' => 3, 'clue_id' => $clue_info['id'], 'adv_id' => $clue_info['adv_id'], 'pro_id' => $pro_id, 'city' => $clue_info['city'], 'create_time' => time()]);
//                }
//                return ['code' => 0, 'msg' => $errMsg];
                if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
//                if($clue_info['type']==1){
//                    return ['code' => 0, 'msg' => $errMsg];
//                }
                    $clue_info['city'] = $clue_info['clue_city'];
                    $clue_info['next_city'] = $clue_info['clue_city'];
                    return $this->getPushRule($clue_info, 1, false);
                } else {
                    return ['code' => 0, 'msg' => $errMsg];
                }
            }

            // 手机MD5排重包过滤
            foreach ($pushs as $k => $v) {
                if (!empty($v['mobile_pack_id'])) {
                    $mobile_pack_ids = explode(',', $v['mobile_pack_id']);
                    if (!empty($mobile_pack_ids)) {
                        $is_exist = \db('mobile_pack_list')
                            ->alias('plist')
                            ->join('mobile_pack p', 'plist.pack_id = p.id')
                            ->where('plist.mobile_md5', md5($clue_info['phone']))
                            ->where('plist.pack_id', 'in', $mobile_pack_ids)
                            ->where('p.status', 1)
                            ->find();
                        if ($is_exist) {
                            unset($pushs[$k]);
                        }
                    }
                }
            }
            if (empty($pushs)) {
                // 都超过了每日接收上限
                $errMsg = '线索手机号与手机MD5包有重复';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $pushInfo);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);

                if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
                    $clue_info['city'] = $clue_info['clue_city'];
                    $clue_info['next_city'] = $clue_info['clue_city'];
                    return $this->getPushRule($clue_info, 1, false);
                } else {
                    return ['code' => 0, 'msg' => $errMsg];
                }
            }

            $account_id=Db::name('account')->where('adv_id',$clue_info['adv_id'])->value('id');
            foreach ($pushs as $k => $v) {
                //如果规则设置了渠道
                if($v['type']==1){
                    if (!empty($v['channel_id'])) {
                        $channelArr=explode(',',$v['channel_id']);
                        if (!in_array($clue_info['type'],$channelArr)) {
                            unset($pushs[$k]);
                        }
                    }
                }elseif ($v['type']==2){
                    if (!empty($v['account_id'])) {
                        $channelArr=explode(',',$v['account_id']);
                        if (!in_array($account_id,$channelArr)) {
                            unset($pushs[$k]);
                        }
                    }
                }
            }

            if (empty($pushs)) {
                // 都超过了每日接收上限
                $errMsg = '商户接受规则与线索渠道不符';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $pushInfo);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                if ($isFirst) {
                    Db::name('clue_err_log')->insert(['type' => 3, 'clue_id' => $clue_info['id'], 'adv_id' => $clue_info['adv_id'], 'pro_id' => $pro_id, 'city' => $clue_info['city'], 'create_time' => time()]);
                }
//                return ['code' => 0, 'msg' => $errMsg];
                if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
//                if($clue_info['type']==1){
//                    return ['code' => 0, 'msg' => $errMsg];
//                }
                    $clue_info['city'] = $clue_info['clue_city'];
                    $clue_info['next_city'] = $clue_info['clue_city'];
                    return $this->getPushRule($clue_info, 1, false);
                } else {
                    return ['code' => 0, 'msg' => $errMsg];
                }
            }
            // 3.根据分发规则计算商户分发量，考虑【撞库线索，继续推送】
            $where = [
                'city' => $clue_info['city'],
                'pro_id' => $clue_info['pro_id'],
                'create_time' => ['between', [strtotime(date('Y-m-d')), time()]]
//                'create_time'=>['between',[strtotime(date('Y-m-d',strtotime('-5 day'))),time()]]
            ];

            // 4 判断每日接收上限
            foreach ($pushs as $k => $v) {
                // 查询每个商户历史推送条数
                $where['mer_id'] = $v['mer_id'];
                $pushs[$k]['count'] = Db::name('clue_log')->where($where)->count();

                if ($v['up_limit'] <= $pushs[$k]['count']) {
                    unset($pushs[$k]);
                }
            }
            if (!empty($pushs)) {
                // 5 计算多商户接收
//                    $push = $this->pushOffset($pushs,$clue_info);
                //新版
                $push = $this->pushOffset2($pushs, $clue_info, [], $isFirst,$nextCity);
//                dump($push);
            } else {
                // 都超过了每日接收上限
                $errMsg = '满足规则商户超出每日接收上限';
                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), $errMsg, $pushs);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
//                return ['code' => 0, 'msg' => $errMsg];
                if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
//                if($clue_info['type']==1){
//                    return ['code' => 0, 'msg' => $errMsg];
//                }
                    $clue_info['city'] = $clue_info['clue_city'];
                    $clue_info['next_city'] = $clue_info['clue_city'];
                    return $this->getPushRule($clue_info, 1, false);
                } else {
                    return ['code' => 0, 'msg' => $errMsg];
                }
            }
        }

//        dump($nextCity);
//        dump($push);

        return ['code' => 1, 'data' => $push];
    }

    //新版过滤规则
    public function pushOffset2($pushs, $clue_info, $listPush = [], $isFirst = false,$nextCity=0)
    {
        //排除之前得规则
        foreach ($pushs as $k => $v) {
            foreach ($listPush as $vv) {
                if ($pushs['id'] == $vv['id']) {
                    unset($pushs[$k]);
                }
            }
        }
        //手机重复过滤 商户状态时间
        $isPushs = $this->isAgentPush2($pushs, $clue_info, $isFirst);

        $rePushs = [];
        foreach ($isPushs as $k => $v) {
            if (isset($v['isPush']) && $v['isPush'] == 1) {
                $rePushs[] = $v;
            }
        }
        $push = [];

        if ($rePushs) {
            //最后一次推送时间
            // 先取出要排序的字段的值
            shuffle($rePushs);
            $sort = array_column($rePushs, 'last_time');
// 按照sort字段升序  其中SORT_ASC表示升序 SORT_DESC表示降序
            array_multisort($sort, SORT_ASC, $rePushs);
            $push = $rePushs[0];
        }else{
            if (!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city'] && $nextCity == 0) {
//                if($clue_info['type']==1){
//                    return ['code' => 0, 'msg' => $errMsg];
//                }
                $clue_info['city'] = $clue_info['clue_city'];
                $clue_info['next_city'] = $clue_info['clue_city'];
                $res=$this->getPushRule($clue_info, 1, false);
                if($res['code']==1){
                    $push= $res['data'];
                }
            }
        }
        return $push;

    }

    public function isAgentPush2($pushs, $clue_info, $isFirst = false)
    {
        $clue_continue_push = Db::name('system_config')->field('status')->where(['_key' => 'clue_continue_push'])->find();
        $status = $clue_continue_push['status'];
        $count = count($pushs);

        foreach ($pushs as $k => $v) {
            $pushs[$k]['isPush'] = 0;
            $merchant = model('Merchant')->getArrayByMap(['id' => $v['mer_id']]);
            if ($merchant) {

                // 判断是否开启撞库
                if ($status == 1) {
                    //同一个商户去重
                    $log=Db::name('clue_log')->where(['mer_id' => $v['mer_id'], 'phone' => $clue_info['phone']])->order('id desc')->find();
                    if ($log) {
                        //看是否超过一个月
                        if (time() < $log['create_time'] + 3600 * 24 * 30) {
                            ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '该城市的商户已经推送过一条相同数据', $v);
                            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '该城市的商户已经推送过一条相同数据']);
                        } else {
                            //看是否余额够
                            if ($merchant['balance'] > 50) {
                                $pushs[$k]['isPush'] = 1;
                            } else {
                                ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '账户币余额不足', $v);
                                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '账户币余额不足']);
                            }
                        }

                    } else {
                        //看是否余额够
                        if ($merchant['balance'] > 50) {
                            $pushs[$k]['isPush'] = 1;
                        } else {
                            ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '账户币余额不足', $v);
                            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '账户币余额不足']);
                        }
                    }
                } else {
                    //看是否余额够
                    if ($merchant['balance'] > 50) {
                        $pushs[$k]['isPush'] = 1;
                    } else {
                        ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '账户币余额不足', $v);
                        model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '账户币余额不足']);
                    }
                }
            }
        }
        return $pushs;
    }

    // 根据商户api地址做推送
    public function sendMerchantClue($push, $clue_info, $findPush = 0,$listPush=[])
    {

        if ($clue_info['status'] == 1) {
            ClueErrorLog::record($clue_info['clue_id'] ?? time() . mt_rand(1000, 9999), '该线索已推送过', $push);
            return '该线索已推送过';
        }

        if (!empty($clue_info['show_city'])) {
            if (strpos($clue_info['show_city'], '|') !== false) {
                $city_t = explode('|', $clue_info['show_city']);
            } elseif (strpos($clue_info['show_city'], '-') !== false) {
                $city_t = explode('-', $clue_info['show_city']);
            } else {
                $city_t = [$clue_info['show_city']];
            }
            $city_info = clue_city_transform($city_t);
            if(empty($city_info)){
                ClueErrorLog::record($push['clue_id'] ?? time() . mt_rand(1000, 9999), '读取商户接收规则失败', $push);
                return '显示城市匹配错误';
            }else{
                $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
                $clue_info['show_city']=$province['id'] . '-' . $city_info['id'];
            }

        }

        //分发执行量
        $errPushLog=[
            'clue_id'=>$clue_info['id'],
            'push_id'=>$push['id'],
            'mer_id'=>$push['mer_id'],
            'city'=>$push['city'],
            'pro_id'=>$push['pro_id'],
            'create_time'=>time(),
        ];
        Db::name('clue_err_push_log')->insert($errPushLog);
        // 1.读取商户接收规则，
        $mapping = model('Mapping')->getArrayByMap(['mer_id' => $push['mer_id']], '', '', false);
        $clue_info['is_find'] = $findPush;

        if (empty($mapping) || empty($mapping['api_url'])) {
            //没有配置三方推送地址
            $res = [];
            $params=[];
            $pushType = 0;
        } else {

            // 手动修改推送城市 增加临时变量 城市 start
            $new_city = $clue_info['city'] ?? "";
            $new_show_city = $clue_info['show_city'] ?? "";

            $pushType = 1;
            // api_key存在走单独api接口，为空则走通用接口
            if ($mapping['api_key']) {
                $class = "\app\api\controller\\v1\\" . ucfirst($mapping['api_key']);
                if (class_exists($class)) {
                    // 手动推送城市
                    if (!empty($clue_info['show_city'])) {
                        $clue_info['city'] = $clue_info['show_city'];
                        unset($clue_info['show_city']);
                    }
                    $instance = new $class();
                    // 2. 推送线索
                    $clue_info['push_id']=$push['id'];
                    $res = $instance->pushClue($mapping, $clue_info,$listPush);
                    $params = $res['params'];
                    unset($res['params']);
                } else {
                    ClueErrorLog::record($push['clue_id'] ?? time() . mt_rand(1000, 9999), '未获取到api类', $mapping);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '未获取到api类']);
                    return '获取到api类';
                }
            } else {
                $api_url = $mapping['api_url'];
                $clue_rule = json_decode($mapping['rule_json'], true);
                $params = [];
                if (!$clue_rule) {
                    ClueErrorLog::record($push['clue_id'] ?? time() . mt_rand(1000, 9999), '读取商户接收规则失败', $push);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => '读取商户接收规则失败']);
                    return '读取商户接收规则失败';
//                    return false;
                } else {
                    // 手动推送城市
                    if (!empty($clue_info['show_city'])) {
                        $clue_info['city'] = $clue_info['show_city'];
                        unset($clue_info['show_city']);
                    }
                    foreach ($clue_rule as $v) {
                        $params[$v['curr']] = $clue_info[$v['orig']];
                        if ($v['orig'] == 'city') {
                            $citys = explode('-', $clue_info[$v['orig']]);
                            $city_info = Db::name('city')->where(['type' => 2, 'id' => $citys[1]])->find();
                            $params[$v['curr']] = $city_info['name'];
                        }
                    }
                    // 2. 推送线索
                    $res = postJson($api_url, $params);
                }
            }

            // 手动修改推送城市 增加临时变量 城市 start
            if (!empty($new_city)) {
                $clue_info['city'] = $new_city;
            }
            if (!empty($new_show_city)) {
                $clue_info['show_city'] = $new_show_city;
            }
        }

        if($push['mer_id']==config('ts_mer_id')){
            // 3. 推送成功后，并修改线索状态和时间
            model('Clue')->where('id', $clue_info['id'])->update(['push_time' => time(), 'is_not_push' => 1]);
            model('Push')->where('id', $push['id'])->update(['last_time' => time()]);
        }else{
            // 3. 推送成功后，并修改线索状态和时间
            model('Clue')->where('id', $clue_info['id'])->update(['push_time' => time(), 'status' => 1]);
            model('Push')->where('id', $push['id'])->update(['last_time' => time()]);
        }


        // 4. 推送成功后，并记录日志
        $clue_log_add = [
            'clue_id' => $clue_info['id'],
            'ad_clue_id' => $clue_info['clue_id'],
            'adv_id' => $clue_info['adv_id'],
            'site_url' => $clue_info['site_url'],
            'push_id' => $push['id'],
            'mer_id' => $push['mer_id'],
            'pro_id' => $push['pro_id'],
            'charge_type' => $push['charge_type'],
            'price' => $push['price'],
            'city' => $clue_info['city'],
            'clue_name' => $clue_info['clue_name'],
            'phone' => $clue_info['phone'],
            'push_type' => $pushType,
            'is_find' => $findPush,
        ];


        if (!empty($clue_info['show_city'])) {
            $clue_log_add['show_city'] = $clue_info['show_city'];
        }
        if (!empty($clue_info['push_channel'])) {
            $clue_log_add['push_channel'] = $clue_info['push_channel'];
        }

        if (is_array($res)) {
            $res = json_encode($res, JSON_UNESCAPED_UNICODE);
        }

        $requests = [
            'clue_id' => $clue_info['id'],
            'mer_id' => $push['mer_id'],
            'clue_name' => $clue_info['clue_name'],
            'req' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'res' => $res,
        ];

        if($push['mer_id']==config('ts_mer_id')){
            $res_log = model('ClueLogNotPush')->create($clue_log_add);
        }else{
            $res_log = model('ClueLog')->create($clue_log_add);
        }

        $merInfo=Db::name('merchant')->where('id', $push['mer_id'])->find();
        // 通知线索用户 公司短信
        $clue_createtime = \db('clue')->where('id', $clue_info['id'])->value('create_time');
        if (!empty($merInfo['company']) && (time() <= $clue_createtime + 300)) { // 公司名不能为空 推送时间间隔不能超过5分钟 短信内容不加签名
            $account_info = \db('account')->where('adv_id', $clue_info['adv_id'])->find();
            SmsMuSend::send($clue_info['phone'],'【'.config('database')['host_sms_name'].'】'."您的申请已接收，将授权我们合作的居间机构“{$merInfo['company']}”为您服务，请留意接听来电");
        }

        //减少余额
        $merMoney=$merInfo['balance'];
        $endMoney=bcsub($merMoney,$push['price'],2);
        $msg_mer_min_money = Db::name('system_config')->field('status,extra')->where(['_key' => 'msg_mer_min_money'])->find();
        if(!empty($msg_mer_min_money)&&$msg_mer_min_money['status']==1){
            Db::name('merchant')->where('id', $push['mer_id'])->dec('balance', $push['price'])->dec('balance2',$push['price'])->update();
            if($merMoney>$msg_mer_min_money['extra']&&$endMoney<=$msg_mer_min_money['extra']){
                $msg_mer_min_type = Db::name('system_config')->field('status,extra')->where(['_key' => 'msg_mer_min_type'])->find();
                if(!empty($msg_mer_min_type)&&$msg_mer_min_type['status']==1){
                    $msgData=[];
                    $msgTypeArr=explode(',',$msg_mer_min_type['extra']);
                    foreach ($msgTypeArr as $v){
                        $msgData[]=['role_type'=>1,'msg_type'=>$v,'a_id'=>$push['mer_id'],'title'=>config('database')['host_sms_name'].'余额不足','content'=>'余额不足'.$msg_mer_min_money['extra'].'元，请及时充值，以免停止推送！【注意：余额太少后推送线索速度会变慢】'];
                        if($v==4){//发送短信
                            if (request()->domain()!=config('testdomain')) {
                                $sendPhone=$merInfo['phone'];
                                if(!empty($sendPhone)&&strlen($sendPhone)==11){
                                    $mobiles=$sendPhone;
//                                    $content='【'.config('database')['host_sms_name'].'】'.'橙焦广告账户币余额'.$endMoney.'，请及时充值【余额太少会影响分发速度】';
                                    $content='【'.config('database')['host_sms_name'].'】'.'账户Yu额:'.$endMoney.'，请及时充值！！';
                                    $extno='';
                                    $sendtime='';
//                                    $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                                    $sendRes=SmsMuSend::send($mobiles,$content);
                                }
                                //商务
                                $adminPhone=Db::name('admin')->where('id',$merInfo['bind_aid'])->value('tel');
                                if(!empty($adminPhone)&&strlen($adminPhone)==11){
                                    $mobiles=$adminPhone;
//                                    $content='【'.config('database')['host_sms_name'].'】'.'商户'.$merInfo['mer_name'].'，余额'.$endMoney.' ,请及时催续';
                                    $content='【'.config('database')['host_sms_name'].'】'.'商户:'.$merInfo['mer_name'].';粮草Yu额:'.$endMoney.' ，请及时续!!';
                                    $extno='';
                                    $sendtime='';
//                                    $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                                    $sendRes=SmsMuSend::send($mobiles,$content);
                                }

                            }
                        }
                    }
                    if(!empty($msgData)){
                        model('MsgNotice')->saveAll($msgData);
                    }
                }
            }

        }else{
            Db::name('merchant')->where('id', $push['mer_id'])->dec('balance', $push['price'])->dec('balance2',$push['price'])->update();
        }

        //余额流水记录
        if($push['price']>0){
            $endMoney2=bcsub($merInfo['balance2'],$push['price'],2);
            $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>2,'type'=>1,'money'=>$push['price'],'balance'=>$endMoney,'create_time'=>time(),'remark'=>'线索消耗'];
            $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>2,'type'=>2,'money'=>$push['price'],'balance'=>$endMoney2,'create_time'=>time(),'remark'=>'线索消耗'];
            Db::name('merchant_balance_log')->insertAll($balanceLog);
        }

//        if($merMoney>=0&&$endMoney<0){
//            Db::name('merchant_owe_money')->insert(['mer_id'=>$push['mer_id'],'money'=>$endMoney,'create_time'=>time()]);
//        }

        if($merMoney>0&&$endMoney<=0&&request()->domain()!=config('testdomain')){
            $sendPhone=$merInfo['phone'];
            if(!empty($sendPhone)&&strlen($sendPhone)==11){
                $mobiles=$sendPhone;
//                $content='【'.config('database')['host_sms_name'].'】'.'橙焦广告账户币余额'.$endMoney.'，请及时充值【余额太少会影响分发速度】';
                $content='【'.config('database')['host_sms_name'].'】'.'账户Yu额:'.$endMoney.'，请及时充值！！';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
            //商务
            $adminPhone=Db::name('admin')->where('id',$merInfo['bind_aid'])->value('tel');
            if(!empty($adminPhone)&&strlen($adminPhone)==11){
                $mobiles=$adminPhone;
//                $content='【'.config('database')['host_sms_name'].'】'.'商户'.$merInfo['mer_name'].'，余额'.$endMoney.' ,请及时催续';
                $content='【'.config('database')['host_sms_name'].'】'.'商户:'.$merInfo['mer_name'].';粮草Yu额:'.$endMoney.' ，请及时续!!';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
            //通知Ycc管理員
            $yccAdminPhone=Db::name('admin')->where('id',6)->value('tel');
            if(!empty($yccAdminPhone)&&strlen($yccAdminPhone)==11){
                $mobiles=$yccAdminPhone;
//                $content='【'.config('database')['host_sms_name'].'】'.'商户'.$merInfo['mer_name'].'，余额'.$endMoney.' ,请及时催续';
                $content='【'.config('database')['host_sms_name'].'】'.'商户:'.$merInfo['mer_name'].';粮草Yu额:'.$endMoney.' ，请及时续!!';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
        }

        //少于1000的时候
        if($merMoney>1000&&$endMoney<=1000&&request()->domain()!=config('testdomain')){
            $sendPhone=$merInfo['phone'];
            if(!empty($sendPhone)&&strlen($sendPhone)==11){
                $mobiles=$sendPhone;
                $content='【'.config('database')['host_sms_name'].'】'.'账户Yu额:'.$endMoney.'，请及时充值！！';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
            //商务
            $adminPhone=Db::name('admin')->where('id',$merInfo['bind_aid'])->value('tel');
            if(!empty($adminPhone)&&strlen($adminPhone)==11){
                $mobiles=$adminPhone;
                $content='【'.config('database')['host_sms_name'].'】'.'商户:'.$merInfo['mer_name'].';粮草Yu额:'.$endMoney.' ，请及时续!!';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
            //通知Ycc管理員
            $yccAdminPhone=Db::name('admin')->where('id',6)->value('tel');
            if(!empty($yccAdminPhone)&&strlen($yccAdminPhone)==11){
                $mobiles=$yccAdminPhone;
                $content='【'.config('database')['host_sms_name'].'】'.'商户:'.$merInfo['mer_name'].';粮草Yu额:'.$endMoney.' ，请及时续!!';
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
                $sendRes=SmsMuSend::send($mobiles,$content);
            }
        }


        $res_req = model('RequestLog')->create($requests);
//            dump($res_req);
//            if($res_req['code'] != 1000){
//                ClueErrorLog::record($push['clue_id'] ?? time().mt_rand(1000,9999),'线索推送商户后记录请求日志失败',$requests);
//                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>'线索推送商户后记录请求日志失败']);
//            }

        // 5. 根据【是否留存线索】来删除或者修改线索状态，
        $retain_clue = Db::name('system_config')->field('status')->where(['_key' => 'retain_clue'])->find();
        $status = $retain_clue['status'];
        if ($status == 2) {
            $industrys = Db::name('industry')->where('lc_status', '=', 2)->select();
            if ($industrys) {
                $inds = array_column($industrys, 'id');
                $account = Db::name('account')->where('adv_id', '=', $clue_info['adv_id'])->find();
                if ($account) {
                    if (in_array($account['hy_id'], $inds)) {
                        $res_clue_delete = model('Clue')->where('id', '=', $clue_info['id'])->delete();
                        if (!$res_clue_delete) {
                            ClueErrorLog::record($push['clue_id'] ?? time() . mt_rand(1000, 9999), '不留存线索时，删除线索失败', $clue_info);
                        }
                    }
                } else {
                    $res_clue_delete = model('Clue')->where('id', '=', $clue_info['id'])->delete();
                    if (!$res_clue_delete) {
                        ClueErrorLog::record($push['clue_id'] ?? time() . mt_rand(1000, 9999), '不留存线索时，删除线索失败', $clue_info);
                    }
                }
            }
        }
        return true;
    }

    // 单独api推送
    public function apiPushClue()
    {

        $mapping = Db::name('mapping')->find(2);
        $clue_info = Db::name('clue')->find(79);

        (new Dazhi())->pushClue($mapping, $clue_info);
    }

    public function getCityName($id)
    {
        $city = Db::name('city')->where(['id'=>$id])->find();
        return $city['name'];
    }

}